package cqrtplm.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.IterUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.page.PageMethod;
import com.hustcad.plm.basic.log.LogEventEnum;
import com.hustcad.plm.basic.log.TyplmLogger;
import com.hustcad.plm.pdm.common.model.dto.DeleteDTO;
import com.hustcad.plm.pdm.common.model.dto.search.ClassifyQueryParamDTO;
import com.hustcad.plm.pdm.common.model.dto.search.SearchAttributeDTO;
import com.hustcad.plm.pdm.common.model.dto.search.SearchConditionDTO;
import com.hustcad.plm.pdm.common.model.dto.search.TypeConditionDTO;
import com.hustcad.plm.pdm.common.model.vo.search.ResultEntityVO;
import com.hustcad.plm.pdm.common.service.CommonDeleteService;
import com.hustcad.plm.pdm.common.service.search.TyplmClassifySearchService;
import com.hustcad.plm.pdm.common.service.search.TyplmCommonSearchService;
import com.hustcad.plm.pdm.common.util.TyplmSearchBuildUtil;
import com.hustcad.plm.pdm.enumeration.model.dto.EnumDetailDTO;
import com.hustcad.plm.pdm.enumeration.model.vo.EnumerationItemHandleVO;
import com.hustcad.plm.pdm.enumeration.service.TyplmEnumerationItemService;
import com.hustcad.plm.pdm.enumeration.service.TyplmEnumerationService;
import com.hustcad.plm.pdm.file.handler.response.ResponseResult;
import com.hustcad.plm.pdm.file.model.dto.UploadFileDTO;
import com.hustcad.plm.pdm.flowbusiness.model.entity.WorkFlowObjectPackage;
import com.hustcad.plm.pdm.form.model.dto.FormDataDTO;
import com.hustcad.plm.pdm.form.model.dto.FormDataFileMarkDTO;
import com.hustcad.plm.pdm.form.service.TyFormDataExtService;
import com.hustcad.plm.pdm.formusage.model.dto.FormFileDTO;
import com.hustcad.plm.pdm.iba.service.TyplmAttributeValueService;
import com.hustcad.plm.pdm.middle.partbom.service.TyplmPdmPartService;
import com.hustcad.plm.pdm.partbom.dto.InsertPartDTO;
import com.hustcad.plm.pdm.partbom.dto.PartBomTree;
import com.hustcad.plm.pdm.partbom.enums.PartBomErrorCodeEnum;
import com.hustcad.plm.pdm.partbom.service.TyplmPartService;
import com.hustcad.plm.pdm.partbom.service.partalternate.TyplmPdmPartAlternateService;
import com.hustcad.plm.pdm.partbom.vo.AlternateInfoVO;
import com.hustcad.plm.pdm.partbom.vo.PartBomTreeByFilterVO;
import com.hustcad.plm.pdm.partbom.vo.PartDetailsVO;
import com.hustcad.plm.pdm.partbom.vo.PdmPartInfoVO;
import com.hustcad.plm.pdm.type.service.TyplmTypeService;
import com.hustcad.plm.pdm.user.model.dto.PdmUserDTO;
import com.hustcad.plm.pdm.user.model.dto.PrincipalParamDTO;
import com.hustcad.plm.pdm.user.model.vo.OrgExtVO;
import com.hustcad.plm.pdm.user.service.TyOrgExtService;
import com.hustcad.plm.pdm.user.service.TyplmGroupService;
import com.hustcad.plm.pdm.user.service.TyplmPrincipalService;
import com.hustcad.plm.pdm.workflow.model.dto.AdvancedFlowContainerCondition;
import com.hustcad.plm.pdm.workflow.model.entity.UserTaskDTO;
import com.hustcad.plm.pdm.workflow.model.entity.WorkFlow;
import com.hustcad.plm.pdm.workflow.model.entity.WorkFlowContainerView;
import com.hustcad.plm.pdm.workflow.model.vo.AdvancedFlowContainerVO;
import com.hustcad.plm.pdm.workflow.service.TyplmWorkFlowContainerService;
import com.hustcad.plm.pdm.workflow.service.TyplmWorkFlowService;
import com.hustcad.plm.pdm.workflow.service.errormark.TyplmCommonErrorMarkService;
import com.ty.basic.constant.TableTypeConstrant;
import com.ty.basic.entity.CTyEntityBaseDO;
import com.ty.basic.entity.IdentifierEntity;
import com.ty.basic.entity.PrincipalEntity;
import com.ty.basic.entity.audit.AuditLogDO;
import com.ty.basic.entity.form.FormDataDO;
import com.ty.basic.entity.org.GroupDO;
import com.ty.basic.entity.org.UserDO;
import com.ty.basic.entity.part.PartDO;
import com.ty.basic.handler.exceptionhandler.exception.ResponseCodeEnum;
import com.ty.basic.handler.exceptionhandler.exception.TyException;
import com.ty.basic.service.snow.SnowflakeIdComponent;
import com.ty.basic.session.TyAccountContext;
import com.ty.basic.util.EntityBaseUtil;
import com.ty.basic.utils.ArgumentUtils;
import com.ty.basic.utils.PageSizeUtil;
import com.ty.basic.vo.AttributeVO;
import com.ty.basic.vo.TyAttributeDefMapVO;
import cqrtplm.common.CommonService;
import cqrtplm.constant.RTErrorCodeEnum;
import cqrtplm.constant.RTPlmConstant;
import cqrtplm.dto.*;
import cqrtplm.dto.query.CrmApiQueryDTO;
import cqrtplm.dto.query.CustomerQueryDTO;
import cqrtplm.entity.*;
import cqrtplm.mapper.*;
import cqrtplm.service.*;
import cqrtplm.util.FormDataGenerator;
import cqrtplm.vo.*;
import lombok.Data;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.actuate.autoconfigure.info.InfoContributorAutoConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;


import javax.annotation.Resource;
import java.math.BigInteger;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static cqrtplm.constant.RTTableTypeConstant.*;

/**
 * @author 博
 * @description 针对表【RT_CFG_STATUS_INFO】的数据库操作Service实现
 * @createDate 2025-06-30 22:04:43
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class RtCfgStatusInfoServiceImpl extends ServiceImpl<RtCfgStatusInfoMapper, RtCfgStatusInfoDO>
        implements RtCfgStatusInfoService {

    //    private String jsonXqzt = "{\"folderName\":\"需求状态表\",\"folderId\":\"707925071160557568\",\"folderPath\":\"/开发人员专用/需求状态表\",\"containerID\":\"707053057766981632\",\"containerType\":\"ty.inteplm.product.CTyPDMLinkProduct\",\"containerName\":\"开发人员专用\",\"productPath\":\"开发人员专用\",\"typeOid\":\"707925305089474560\",\"typeName\":\"状态需求表\",\"classId\":\"\",\"classDisplayName\":\"\",\"productID\":\"707053057766981632\",\"typeOType\":\"ty.inteplm.part.CTyPart|状态需求表\",\"lifecycleTemplate\":\"基本生命周期\",\"partNumber\":\"part202507291015361246028\",\"lifecycleTemplateID\":\"716379040738459648\",\"lifecycleTemplateName\":\"基本生命周期\",\"partView\":\"Design\",\"Stage\":\"\",\"BusinessEdition\":\"\",\"ChangeContent\":\"\",\"productType\":\"机型444\",\"devCode\":\"开发令444\",\"number\":\"part202507291015361246028\",\"name\":\"名称444\",\"description\":\"描述444\",\"collapsible\":\"0\",\"unit\":\"PCS\",\"lockdate\":\"\",\"checkoutState\":\"\",\"lifecycleState\":\"Creating\",\"lifecycleMasterName\":\"基本生命周期\",\"ownername\":\"\",\"creatorName\":\"\",\"机型\":\"\",\"ibaAttribute\":{\"Stage\":[\"\"],\"BusinessEdition\":[\"\"],\"ChangeContent\":[\"\"],\"productType\":[\"机型444\"],\"devCode\":[\"开发令444\"],\"机型\":[\"\"]}}";
    private String jsonXqzt183 = "{\"folderName\":\"需求状态表\",\"folderId\":\"748981769688678400\",\"folderPath\":\"/需求状态表/需求状态表\",\"containerID\":\"748981727594643456\",\"containerType\":\"ty.inteplm.product.CTyPDMLinkProduct\",\"containerName\":\"需求状态表\",\"productPath\":\"需求状态表\",\"typeOid\":\"725884644494311424\",\"typeName\":\"状态需求表\",\"classId\":\"720075261332832256\",\"classDisplayName\":\"X-电焊机\",\"productID\":\"748981727594643456\",\"typeOType\":\"ty.inteplm.part.CTyPart|StatusRequirementsTable\",\"partView\":\"Design\",\"lifecycleTemplate\":\"润通通用生命周期模板\",\"partNumber\":\"part202510251454300665755\",\"lifecycleTemplateID\":\"751073324083789824\",\"lifecycleTemplateName\":\"润通通用生命周期模板\",\"number\":\"part202510251454300665755\",\"name\":\"2222\",\"collapsible\":\"0\",\"productType\":\"2222\",\"devCode\":\"X46\",\"ibaAttribute\":{\"productType\":[\"2222\"],\"devCode\":[\"X46\"]}}";
    private static final String KEY_WORD_JSON = "{\"keyWord\":\"WT202509170011\",\"myCreate\":1,\"myJoin\":1,\"myWatch\":0,\"myManage\":0,\"workflowIdSet\":[],\"includeTY\":0,\"type\":\"\",\"statusOutZero\":\"\",\"emergencydegree\":\"\",\"creatorOid\":\"\",\"operatorOid\":\"\",\"remark\":\"\",\"createStartDate\":\"\",\"createEndDate\":\"\",\"startStartDate\":\"\",\"startEndDate\":\"\",\"completeStartDate\":\"\",\"completeEndDate\":\"\",\"containerSet\":[{\"oid\":\"\",\"otype\":\"ty.inteplm.product.CTyPDMLinkProduct\"},{\"oid\":\"\",\"otype\":\"ty.inteplm.library.CTyLibrary\"},{\"oid\":\"\",\"otype\":\"ty.inteplm.project.CTyProject\"},{\"oid\":\"\",\"otype\":\"ty.inteplm.domain.CTyOrgContainer\"}],\"pageNum\":1,\"pageSize\":20,\"columns\":[{\"propertyName\":\"code\",\"displayName\":\"流程编号\",\"masterProperty\":false,\"fixed\":\"left\",\"width\":\"180\",\"sortable\":false,\"fieldList\":[],\"virtual\":false,\"foreignColumnMaster\":false,\"canNotRemove\":false,\"enum\":false},{\"propertyName\":\"name\",\"displayName\":\"流程名称\",\"masterProperty\":false,\"fixed\":\"left\",\"width\":\"180\",\"sortable\":false,\"fieldList\":[],\"virtual\":false,\"foreignColumnMaster\":false,\"canNotRemove\":false,\"enum\":false},{\"propertyName\":\"remark\",\"displayName\":\"流程描述\",\"masterProperty\":false,\"width\":\"120\",\"sortable\":false,\"fieldList\":[],\"virtual\":false,\"foreignColumnMaster\":false,\"canNotRemove\":false,\"enum\":false},{\"propertyName\":\"workflowName\",\"displayName\":\"流程模板\",\"masterProperty\":false,\"width\":\"160\",\"sortable\":false,\"fieldList\":[],\"virtual\":false,\"foreignColumnMaster\":false,\"canNotRemove\":false,\"enum\":false},{\"propertyName\":\"statusName\",\"displayName\":\"流程状态\",\"masterProperty\":false,\"width\":\"80\",\"sortable\":false,\"fieldList\":[],\"virtual\":false,\"foreignColumnMaster\":false,\"canNotRemove\":false,\"enum\":false},{\"propertyName\":\"taskName\",\"displayName\":\"当前节点\",\"masterProperty\":false,\"width\":\"80\",\"sortable\":false,\"fieldList\":[],\"virtual\":false,\"foreignColumnMaster\":false,\"canNotRemove\":false,\"enum\":false},{\"propertyName\":\"taskUserName\",\"displayName\":\"未执行人\",\"masterProperty\":false,\"width\":\"100\",\"sortable\":false,\"fieldList\":[],\"virtual\":false,\"foreignColumnMaster\":false,\"canNotRemove\":false,\"enum\":false},{\"propertyName\":\"creatorName\",\"displayName\":\"发起者\",\"masterProperty\":false,\"width\":\"100\",\"sortable\":false,\"fieldList\":[],\"virtual\":false,\"foreignColumnMaster\":false,\"canNotRemove\":false,\"enum\":false},{\"propertyName\":\"createStamp\",\"displayName\":\"发起时间\",\"masterProperty\":false,\"width\":\"140\",\"sortable\":false,\"fieldList\":[],\"virtual\":false,\"foreignColumnMaster\":false,\"canNotRemove\":false,\"enum\":false},{\"propertyName\":\"type\",\"displayName\":\"流程类型\",\"masterProperty\":false,\"width\":\"80\",\"sortable\":false,\"fieldList\":[],\"virtual\":false,\"foreignColumnMaster\":false,\"canNotRemove\":false,\"enum\":false}]}";

    @Resource
    private CommonDeleteService commonDeleteService;
    @Resource
    private TyplmLogger typlmLogger;

    @Resource
    private TyplmCommonSearchService typlmCommonSearchService;
    @Resource
    private RtCfgStatusInfoService rtCfgStatusInfoService;
    @Resource
    private RtCfgStatusInfodetailService rtCfgStatusInfodetailService;
    @Resource
    private RtCfgStatusInfodetailMapper rtCfgStatusInfodetailMapper;
    @Resource
    private DspfStatusModuleitemsubMapper dspfStatusModuleitemsubMapper;
    @Resource
    private DspfStatusModuleitemService dspfStatusModuleitemService;
    @Resource
    private TyplmPdmPartAlternateService typlmPartAlternateService;
    @Resource
    private RtCfgStatusInfoMapper rtCfgStatusInfoMapper;
    @Resource
    private DspfStatusModuleitemsubServiceImpl dspfStatusModuleitemsubServiceImpl;
    @Resource
    private TyplmPrincipalService typlmPrincipalService;
    @Resource
    private SnowflakeIdComponent snowflakeIdComponent;
    @Resource
    private TyplmEnumerationItemService typlmEnumerationItemService;
    @Resource
    private RtTestRequirementsService rtTestRequirementsService;
    @Resource
    private RTEngraveMapper rtEngraveMapper;
    @Resource
    private TyplmAttributeValueService typlmAttributeValueService;
    @Resource
    private TyplmClassifySearchService typlmClassifySearchService;
    @Resource
    private TyplmPartService typlmPartService;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Resource
    private IRtCfgDspfDemandMainService iRtCfgDspfDemandMainService;
    @Resource
    private RtCfgTemplatecontentConstraintsMapper rtCfgTemplatecontentConstraintsMapper;
    @Resource
    private RtCfgTemplatecontentConstraintsServiceImpl rtCfgTemplatecontentConstraintsServiceImpl;
    @Resource
    private TyplmPdmPartService typlmPdmPartService;
    @Resource
    private RtCfgDspfDemandMainMapper rtCfgDspfDemandMainMapper;
    @Resource
    private RtCfgBomMapper rtCfgBomMapper;
    @Resource
    private CrmApiService crmApiService;
    @Resource
    private TyplmWorkFlowContainerService typlmWorkFlowContainerService;
    @Resource
    private TyplmWorkFlowService typlmWorkFlowService;
    @Resource
    private TyOrgExtService orgExtService;
    @Resource
    private DevOrderService devOrderService;
    @Resource
    private TyplmTypeService typlmTypeService;
    @Resource
    private TyplmGroupService typlmGroupService;
    @Resource
    private DspfMbomBomMapper dspfMbomBomMapper;
    @Resource
    private TyFormDataExtService tyFormDataExtService;
    @Resource
    private IRtCfgSerialNumberService serialNumberService;
    @Resource
    private RatoCpytService ratoCpytService;
    @Resource
    private RtCfgMzMapper rtCfgMzMapper;
    @Resource
    private TyplmEnumerationService typlmEnumerationService;
    @Resource
    private CommonService commonService;
    //机型内部名称
    @Value("${STATUS_INFO_PARTTYPE}")
    private String STATUS_INFO_PARTTYPE;
    //开发令
    @Value("${STATUS_INFO_DEVCODE}")
    private String STATUS_INFO_DEVCODE;
    //终端机组负责人内部名称
    @Value("${STATUS_INFO_MODELMANAGERZD}")
    private String STATUS_INFO_MODELMANAGERZD;
    //终端动力负责人内部名称
    @Value("${STATUS_INFO_MODELMANAGERDL}")
    private String STATUS_INFO_MODELMANAGERDL;
    //参考类型内部名称
    @Value("${STATUS_INFO_REFTYPE}")
    private String STATUS_INFO_REFTYPE;
    //物料对象类型的内部名称
    @Value("${STATUS_INFO_OBJECTTYPE}")
    private String STATUS_INFO_OBJECTTYPE;
    //图样代号对象类型的内部名称
    @Value("${STATUS_INFO_ENUMERATIONTYPE}")
    private String STATUS_INFO_ENUMERATIONTYPE;


    private final String TEMPLATENAME = "状态需求表审批流程2";


    @Autowired
    private InfoContributorAutoConfiguration infoContributorAutoConfiguration;

    @Override
    public ResponseResult getModuleIdByModelAndDevelopmentOrder(RtCfgStatusDTO dto) throws ParseException {
        if (StringUtils.isBlank(dto.getProducttype()) || StringUtils.isBlank(dto.getDevcode())) {
            throw RTErrorCodeEnum.COMPLETE_DRAW_ERROR.getException("开发令/机型为空!");
        }

        String objectNumber = rtCfgStatusInfoMapper.selectMoudleByProductType(STATUS_INFO_PARTTYPE,
                                                                              dto.getProducttype(),
                                                                              STATUS_INFO_DEVCODE,
                                                                              dto.getDevcode());

        if (StringUtils.isBlank(objectNumber)) {
            throw RTErrorCodeEnum.COMPLETE_DRAW_ERROR.getException("未查询到相关的产品型谱对象！");
        }

        List<String> alternateForPartNumbers = Arrays.asList(objectNumber);
        List<AlternateInfoVO> alternateInfoVOS = typlmPartAlternateService.batchQueryAlternates(
                alternateForPartNumbers);

        List<TemplateInfoVO> oids = new ArrayList<>();
        for (AlternateInfoVO alternateInfoVO : alternateInfoVOS) {
            TemplateInfoVO templateInfoVO = new TemplateInfoVO(
                    String.valueOf(alternateInfoVO.getAlternateObjectMasterOid()),
                    alternateInfoVO.getAlternatempnname());
            if (templateInfoVO != null) {
                oids.add(templateInfoVO);
            }
        }

        if (oids.isEmpty()) {
            throw RTErrorCodeEnum.COMPLETE_DRAW_ERROR.getException("未查询到绑定的需求模板，请重新再试！");
        }
        if (oids.size() > 1) {
            throw RTErrorCodeEnum.COMPLETE_DRAW_ERROR.getException("该开发令和机型绑定了多个模板！");
        }
        return ResponseResult.success(oids, "");
    }

    @Override
    public ResponseResult getRtCfgStatusInfoByModuleIdOrStatusCode(RtCfgStatusDTO dto) {
        // 参数校验
        //        if (dto.getFatherOid() == null) {
        //            return ResponseResult.fail("", "500", "fatherOid不能为空");
        //        }
        //获取需求状态模板编码
        String modelManagerZd = "";
        String modelManagerDl = "";


        boolean hasModuleAndProductType = StrUtil.isNotBlank(dto.getModuleId()) && StrUtil.isNotBlank(
                dto.getProducttype());
        boolean hasStatusCodeOrOid = StrUtil.isNotBlank(dto.getStatusCode()) || StrUtil.isNotEmpty(
                dto.getOid()) || StrUtil.isNotBlank(dto.getStatusid());


        if (hasModuleAndProductType || hasStatusCodeOrOid || StrUtil.isNotBlank(
                dto.getProductCode()) || StrUtil.isNotEmpty(dto.getReferjzmbomcode())) {
            try {
                // 获取当前登录用户信息
                UserDO user = TyAccountContext.getUser();
                if (user == null) {
                    return ResponseResult.fail("", "401", "用户未登录");
                }
                BigInteger userOid = user.getOid();

                RtCfgStatusInfoVO rtCfgStatusInfoVO = new RtCfgStatusInfoVO();

                // 根据成品码查询
                if (StrUtil.isNotBlank(dto.getProductCode()) || StrUtil.isNotEmpty(dto.getReferjzmbomcode())) {
                    //                    String demandCode = rtCfgDspfDemandMainMapper.selectDemandCodeByProductCode(dto.getProductCode());
                    //                    RtCfgStatusInfoDO rtCfgStatusInfoDO = rtCfgStatusInfoMapper.selectStatusInfoByStatusCode(
                    //                            demandCode);
                    //                    if (rtCfgStatusInfoDO == null) {
                    //                        return ResponseResult.fail("", "500", "未查询到需求状态信息！");
                    //                    }
                    //                    fillModelManagers(rtCfgStatusInfoDO, modelManagerZd, modelManagerDl);
                    //                    return buildSuccessResponse(rtCfgStatusInfoVO, rtCfgStatusInfoDO, oid);
                    RtCfgStatusInfoDO statusInfoDO = rtCfgStatusInfoMapper.selectByStatusCode(dto);
                    if (statusInfoDO == null) {
                        throw RTErrorCodeEnum.COMPLETE_DRAW_ERROR.getException(
                                "通过成品码等信息未查询到相关的需求状态表信息");
                    }
                    fillModelManagers(statusInfoDO, modelManagerZd, modelManagerDl);
                    return buildSuccessResponse(rtCfgStatusInfoVO, statusInfoDO, userOid, dto.getWorkFlowOid());
                }
                //
                //                // 根据状态码或oid查询
                if (hasStatusCodeOrOid) {
                    RtCfgStatusInfoDO statusInfoDO = rtCfgStatusInfoMapper.selectByStatusCode(dto);
                    if (statusInfoDO == null) {
                        return ResponseResult.success("通过状态需求表编码/ID等信息未查询到相关的需求表详细信息", "500");
                        //                        throw RTErrorCodeEnum.COMPLETE_DRAW_ERROR.getException("通过状态需求表编码/ID等信息未查询到相关的需求表详细信息");
                    }
                    fillModelManagers(statusInfoDO, modelManagerZd, modelManagerDl);
                    return buildSuccessResponse(rtCfgStatusInfoVO, statusInfoDO, userOid, dto.getWorkFlowOid());
                }

                // 根据模块ID和产品类型查询
                if (hasModuleAndProductType) {
                    rtCfgStatusInfoVO.setDspfStatusModuleitem(
                            dspfStatusModuleitemService.selectByModuleId(dto.getModuleId()));
                    List<DspfStatusModuleitemsubDTO> dspfStatusModuleitemsub = getModuleItemSubList(userOid,
                                                                                                    dto.getModuleId(),
                                                                                                    dto.getWorkFlowOid());
                    rtCfgStatusInfoVO.setDspfStatusModuleitemsub(dspfStatusModuleitemsub);
                    //TODO 现在通过机型和开发令 加模板id  可能会有多套需求状态表  需要确认后续逻辑
                    //                    RtCfgStatusInfoDO rtCfgStatusInfoDO = rtCfgStatusInfoMapper.selectByModuleId(dto);
                    //                    if (rtCfgStatusInfoDO == null) {
                    //                        rtCfgStatusInfoVO.setRtCfgStatusInfo(new RtCfgStatusInfoDO());
                    //                        rtCfgStatusInfoVO.setRtCfgStatusInfodetail(new ArrayList<>());
                    //                        return ResponseResult.success(rtCfgStatusInfoVO, "");
                    //                    }
                    RtCfgStatusInfoDO rtCfgStatusInfoDO = new RtCfgStatusInfoDO();
                    //                    rtCfgStatusInfoVO.setRtCfgStatusInfodetail(
                    //                            rtCfgStatusInfodetailService.selectByInfoId(rtCfgStatusInfoDO.getStatusid()));
                    //                    rtCfgStatusInfoVO = this.handleFileArr(rtCfgStatusInfoVO);
                    fillModelManagers(rtCfgStatusInfoDO, modelManagerZd, modelManagerDl);
                    rtCfgStatusInfoVO.setRtCfgStatusInfo(rtCfgStatusInfoDO);
                    return ResponseResult.success(rtCfgStatusInfoVO, "");
                }

            } catch (Exception e) {
                e.printStackTrace();
                throw RTErrorCodeEnum.COMPLETE_DRAW_ERROR.getException("查询需求状态信息异常");
            }
        }
        throw RTErrorCodeEnum.COMPLETE_DRAW_ERROR.getException("请输入需求模块ID或者需求状态编码");
    }

    @Override
    public ResponseResult getRtCfgStatusInfoByProductCode(RtCfgStatusDTO dto) {
        // 获取当前登录用户信息
        UserDO user = TyAccountContext.getUser();
        if (user == null) {
            return ResponseResult.fail("", "401", "用户未登录");
        }
        BigInteger oid = user.getOid();
        RtCfgStatusInfoVO rtCfgStatusInfoVO = new RtCfgStatusInfoVO();
        RtCfgStatusInfoDO statusInfoDO = rtCfgStatusInfoMapper
                .selectByStatusCode(dto);
        if (ObjectUtil.isEmpty(statusInfoDO)) {
            throw RTErrorCodeEnum.STATUS_INFO_CONTENT_IS_NULL.getException(
                    "未查询到参考成品码【" + dto.getProductCode() + "】的需求状态表数据");
        }
        TemplateInfoVO defaultTemplates = rtCfgStatusInfoMapper
                .getDefaultTemplateLatest(STATUS_INFO_REFTYPE,
                                          MODEL_IBA_TYPE,
                                          "终端变化点");
        if (ObjectUtil.isNotEmpty(defaultTemplates)) {
            statusInfoDO.setModuleid(defaultTemplates.getModuleId());
        }
        return buildSuccessResponse(rtCfgStatusInfoVO, statusInfoDO, oid, dto.getWorkFlowOid());
    }


    // 提取公共填充modelManager的方法
    private void fillModelManagers(RtCfgStatusInfoDO infoDO, String zd, String dl) {
        //获取绑定的开发令和机型
        String devcode = infoDO.getDevcode();
        String producttype = infoDO.getProducttype();
        if (devcode != null && producttype != null) {
            //根据开发令和机型搜索产品型谱
            String objectNumber = rtCfgStatusInfoMapper.selectMoudleByProductType(STATUS_INFO_PARTTYPE,
                                                                                  producttype,
                                                                                  STATUS_INFO_DEVCODE,
                                                                                  devcode);
            if (objectNumber == null) {
                return;
            }
            PartDO partDO = typlmPdmPartService.queryLastPartDoByPartNumber(objectNumber);
            Map<String, List<AttributeVO>> attrValueByOidAndKeys = typlmAttributeValueService.getIbaAttrValueByOidAndKeys(
                    Collections.singletonList(partDO.getOid()),
                    TableTypeConstrant.TY_PART_OTYPE,
                    Collections.singletonList(RTPlmConstant.PRODUCTMANNAME));
            if (attrValueByOidAndKeys != null && attrValueByOidAndKeys.size() > 0) {
                zd = attrValueByOidAndKeys.get(String.valueOf(partDO.getOid())).get(0).getAttributeValue();
                dl = attrValueByOidAndKeys.get(String.valueOf(partDO.getOid())).get(0).getAttributeValue();
            }
        }
        if (zd != null) {
            infoDO.setModelManagerZd(zd);
        }
        if (dl != null) {
            infoDO.setModelManagerDl(dl);
        }
    }

    // 构建成功响应的公共方法
    private ResponseResult buildSuccessResponse(RtCfgStatusInfoVO vo, RtCfgStatusInfoDO infoDO, BigInteger oid,
                                                String workFlowOid) {
        vo.setRtCfgStatusInfo(infoDO);
        List<RtCfgStatusInfodetailDO> rtCfgStatusInfodetailDOS = rtCfgStatusInfodetailService.selectByInfoId(
                infoDO.getStatusid());
        vo.setRtCfgStatusInfodetail(rtCfgStatusInfodetailDOS);
        String moduleid = infoDO.getModuleid();
        List<DspfStatusModuleitemsubDTO> moduleItemSubList = getModuleItemSubList(oid, moduleid, workFlowOid);
        vo.setDspfStatusModuleitemsub(moduleItemSubList);
        List<DspfStatusModuleitemDO> dspfStatusModuleitemDOS = dspfStatusModuleitemService.selectByModuleId(moduleid);
        vo.setDspfStatusModuleitem(dspfStatusModuleitemDOS);
        vo = this.handleFileArr(vo);
        return ResponseResult.success(vo, "");
    }


    private List<DspfStatusModuleitemsubDTO> getModuleItemSubList(BigInteger userOid, String moduleId,
                                                                  String workFlowOid) {
        DspfStatusModuleitemsubDO dspfStatusModuleitemsubDO = new DspfStatusModuleitemsubDO();
        dspfStatusModuleitemsubDO.setModuleId(moduleId);
        Example example = new Example(WorkFlow.class, true, true);
        //通过流程模板名称 获取模板的一些详细信息 这里是获取流程节点里面可以设置的所有用户信息

        example.createCriteria().andEqualTo("name", TEMPLATENAME);
        List<WorkFlow> workFlowList = this.typlmWorkFlowService.simpleQueryListByExample(example);
        if (ObjectUtils.isEmpty(workFlowList)) {
            throw RTErrorCodeEnum.NOT_FOUND_OBJECT_WORK_FLOW_TEMPLATE.getException();
        }
        WorkFlow workFlow = workFlowList.get(0);
        //获取所有流程节点
        List<UserTaskDTO> allUserTask = typlmWorkFlowContainerService.getAllUserTask(workFlow.getOid(),
                                                                                     workFlow.getContainerOid(),
                                                                                     workFlow.getContainerOtype());

        //        String workFlowTaskId = getWorkFlowTaskId(workFlowOid);
        //获取当前节点的所有用户
        if (ObjectUtils.isEmpty(workFlowOid)) {
            //当节点名称为空的时候  那就获取第一个节点的 id
            if (allUserTask != null && !allUserTask.isEmpty()) {
                workFlowOid = allUserTask.get(0).getId();
            }
        }

        // 获取状态名称数据
        List<DspfStatusModuleitemsubDTO> data = (List<DspfStatusModuleitemsubDTO>)
                dspfStatusModuleitemsubServiceImpl.getByDspfStatusModuleitemsub(dspfStatusModuleitemsubDO).getData();
        String workFlowTaskId = workFlowOid;

        // 过滤data数据，并同时过滤每个dto中的list数据
        List<DspfStatusModuleitemsubDTO> filteredData = data.stream()
                .filter(dto -> {
                    // 过滤dto中的list，只保留满足条件的GroupDO
                    List<DspfStatusModuleitemsubgroupDO> filteredList = dto.getList().stream()
                            .filter(groupDO -> {
                                // 检查groupId是否包含多个值（用逗号或分号分隔）
                                if (groupDO.getGroupId() != null) {
                                    // 支持逗号分隔
                                    if (groupDO.getGroupId().contains(",")) {
                                        return Arrays.asList(groupDO.getGroupId().split(",")).contains(workFlowTaskId) && groupDO.getIsDisplayed();
                                    }
                                    // 支持分号分隔
                                    else if (groupDO.getGroupId().contains(";")) {
                                        return Arrays.asList(groupDO.getGroupId().split(";")).contains(workFlowTaskId) && groupDO.getIsDisplayed();
                                    }
                                    // 单个值的情况
                                    else {
                                        return workFlowTaskId.equals(groupDO.getGroupId()) && groupDO.getIsDisplayed();
                                    }
                                }
                                return false;
                            })
                            .collect(Collectors.toList());

                    // 更新dto的list为过滤后的结果
                    dto.setList(filteredList);

                    // 如果filteredList不为空，说明有匹配的GroupDO
                    if (!filteredList.isEmpty()) {
                        // 获取该节点的所有用户
                        List<PdmUserDTO> userList1 = allUserTask.stream()
                                .filter(task -> workFlowTaskId.equals(task.getId()))
                                .findFirst()
                                .map(UserTaskDTO::getUserList)
                                .orElse(Collections.emptyList());

                        // 检查当前登录用户是否在userList中
                        return userList1.stream()
                                .anyMatch(user -> userOid != null && userOid.toString().equals(user.getOid()));
                    }

                    return false;
                })
                .collect(Collectors.toList());

        return filteredData;


    }

    /**
     * 递归查找所有匹配名称的组织节点
     *
     * @param orgList 组织列表
     * @param targetName 目标名称
     * @return 匹配的OrgExtVO对象列表
     */
    private List<OrgExtVO> findAllOrgsByName(List<OrgExtVO> orgList, String targetName) {
        List<OrgExtVO> result = new ArrayList<>();

        if (orgList == null || orgList.isEmpty() || StringUtils.isBlank(targetName)) {
            return result;
        }

        for (OrgExtVO org : orgList) {
            // 检查当前节点名称是否匹配
            if (targetName.equals(org.getName())) {
                result.add(org);
            }

            // 递归检查子节点
            if (org.isHasChildren() && org.getChildList() != null && !org.getChildList().isEmpty()) {
                result.addAll(findAllOrgsByName(org.getChildList(), targetName));
            }
        }

        return result;
    }


    //    public String getWorkFlowTaskId(String toid) {
    //        if (StrUtil.isEmpty(toid)) {
    //            return null;
    //        }
    //
    //        TyAccountContext.setBizCommonHolderMapValue("ignoreUserDisabled", "Y");
    //        try {
    //            //获取流程对象包
    //            WorkFlowObjectPackage workflowobjectPackage = getWorkFlowObjectPackage(new BigInteger(toid));
    //            if (workflowobjectPackage == null) {
    //                return null;
    //            }
    //            //放入流程编码来获取当前节点信息
    //            AdvancedFlowContainerCondition condition = buildCondition(workflowobjectPackage.getCode());
    //            //查询当前流程节点信息
    //            PageInfo<AdvancedFlowContainerVO> pageInfo = this.typlmWorkFlowContainerService.advancedQueryListPage(
    //                    condition);
    //            if (pageInfo == null || pageInfo.getList() == null || pageInfo.getList().isEmpty()) {
    //                return null;
    //            }
    //            //获取当前流程节点id
    //            String taskid = pageInfo.getList().get(0).getTaskDefKey();
    //
    //            return taskid;
    //        } finally {
    //            TyAccountContext.removeBizCommonHolderMapValue("ignoreUserDisabled");
    //        }
    //    }

    //    private AdvancedFlowContainerCondition buildCondition(String code) {
    //        AdvancedFlowContainerCondition condition = JSON.parseObject(KEY_WORD_JSON,
    //                                                                    AdvancedFlowContainerCondition.class);
    //        condition.setKeyWord(code);
    //        return condition;
    //    }

    private WorkFlowObjectPackage getWorkFlowObjectPackage(BigInteger toid) {
        WorkFlowContainerView workFlowContainerView = this.typlmWorkFlowContainerService.getWorkFlowContainerDetailByPrimaryKey(
                toid);
        if (workFlowContainerView == null) {
            return null;
        }

        try {
            return (WorkFlowObjectPackage) workFlowContainerView;
        } catch (ClassCastException e) {
            throw new RuntimeException("对象转换失败", e);
        }
    }

    //    private boolean isUserInGroup(BigInteger userId, BigInteger groupId) {
    //        if (groupId == null) {
    //            return false;
    //        }
    //        PrincipalEntity principalEntity = new PrincipalEntity(groupId, "ty.inteplm.org.CTyGroup");
    //        List<PrincipalEntity> memberList = typlmPrincipalService.getPrincipalOutChildren(principalEntity, null);
    //        return memberList.stream().anyMatch(member -> userId.equals(member.getOid()));
    //    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult saveRtCfgStatusInfo(RtCfgStatusInfoVO rtCfgStatusInfoVO) {
        try {
            //对传输的文件对象处理
            rtCfgStatusInfoVO = this.handleFileArr(rtCfgStatusInfoVO);
            boolean flag = false;
            // 参数校验
            if (rtCfgStatusInfoVO == null || rtCfgStatusInfoVO.getRtCfgStatusInfo() == null) {
                throw RTErrorCodeEnum.COMPLETE_DRAW_ERROR.getException("参数不能为空");
            }
            if (rtCfgStatusInfoVO.getDspfStatusModuleitemsub() != null) {
                flag = true;
            }
            RtCfgStatusInfoDO rtCfgStatusInfoDO = rtCfgStatusInfoVO.getRtCfgStatusInfo();

            //获取模块id
            String moduleId = null;
            List<DspfStatusModuleitemsubDTO> moduleItemSubList = rtCfgStatusInfoVO.getDspfStatusModuleitemsub();
            if (moduleItemSubList != null && !moduleItemSubList.isEmpty() && moduleItemSubList.get(0) != null) {
                moduleId = moduleItemSubList.get(0).getModuleId();
            }
            //根据oid查询masterOid
            String masterOid = this.getMasterOidByOid(rtCfgStatusInfoDO.getFatherOid());
            rtCfgStatusInfoDO.setFatherOid(masterOid);
            UserDO user = TyAccountContext.getUser();
            if (user == null) {
                return ResponseResult.fail("", "401", "用户未登录");
            }

            // 检查数据是否存在
            boolean isMainExist = StringUtils.isNotBlank(rtCfgStatusInfoDO.getStatusid());

            Date now = new Date();
            if (isMainExist) {
                // 更新主表
                rtCfgStatusInfoDO.setFModifydate(now);
                rtCfgStatusInfoDO.setFModifyuserid(String.valueOf(user.getOid()));
                rtCfgStatusInfoDO.setFModifyusername(user.getName());
                rtCfgStatusInfoDO.setModuleid(moduleId);
                if (rtCfgStatusInfoMapper.updateByStatusId(rtCfgStatusInfoDO) <= 0) {
                    throw RTErrorCodeEnum.COMPLETE_DRAW_ERROR.getException("主表更新失败");
                }
            } else {
                // 新增主表
                rtCfgStatusInfoDO.setStatusid(String.valueOf(snowflakeIdComponent.getInstance().nextId()));
                rtCfgStatusInfoDO.setStatus(2);
                rtCfgStatusInfoDO.setFDeletemark(0);
                rtCfgStatusInfoDO.setFEnabledmark(1);
                rtCfgStatusInfoDO.setFCreatedate(now);
                rtCfgStatusInfoDO.setModuleid(moduleId);
                rtCfgStatusInfoDO.setFCreateuserid(String.valueOf(user.getOid()));
                rtCfgStatusInfoDO.setFcreateusername(user.getName());
                rtCfgStatusInfoDO.setMainebomcode(rtCfgStatusInfoDO.getEbomcode());
                List<DspfStatusModuleitemDO> dspfStatusModuleitem = rtCfgStatusInfoVO.getDspfStatusModuleitem();
                if (IterUtil.isNotEmpty(dspfStatusModuleitem)) {
                    rtCfgStatusInfoDO.setModuleid(dspfStatusModuleitem.get(0).getModuleId());
                }
                //新增完成之后需增加底层配置需求状态表 跟info表绑定
                PdmPartInfoVO pdmPartInfoVO = this.savePdmPartInfo(rtCfgStatusInfoVO);
                if (ObjectUtil.isNotEmpty(pdmPartInfoVO)) {
                    rtCfgStatusInfoDO.setOid(pdmPartInfoVO.getOid());
                    rtCfgStatusInfoDO.setOtype(pdmPartInfoVO.getOtype());
                }

                if (rtCfgStatusInfoMapper.insertByRtCfgStatusInfo(rtCfgStatusInfoDO) <= 0) {
                    throw RTErrorCodeEnum.COMPLETE_DRAW_ERROR.getException("主表插入失败");
                }
            }

            // 处理明细数据
            List<RtCfgStatusInfodetailDO> existingDetails = rtCfgStatusInfodetailService.selectByInfoId(
                    rtCfgStatusInfoDO.getStatusid());
            Map<String, RtCfgStatusInfodetailDO> existingDetailMap = existingDetails.stream()
                    .collect(Collectors.toMap(RtCfgStatusInfodetailDO::getDid, detail -> detail));

            List<RtCfgStatusInfodetailDO> detailsToUpdate = new ArrayList<>();
            List<RtCfgStatusInfodetailDO> detailsToInsert = new ArrayList<>();

            //            // 假设这些常量已在类中定义
            //            private static final int DELETE_MARK_NOT_DELETED = 0;
            //            private static final int ENABLED_MARK_ENABLED = 1;

            // 批量获取所有需要更新的 detail 对象
            List<String> didsToUpdate = rtCfgStatusInfoVO.getRtCfgStatusInfodetail().stream()
                    .filter(detail -> existingDetailMap.containsKey(detail.getDid()))
                    .map(RtCfgStatusInfodetailDO::getDid)
                    .collect(Collectors.toList());

            Map<String, RtCfgStatusInfodetailDO> didToDetailMap = new HashMap<>();
            if (!didsToUpdate.isEmpty()) {
                List<RtCfgStatusInfodetailDO> detailList = rtCfgStatusInfodetailMapper.selectByDidList(
                        didsToUpdate); // 新增批量查询接口
                didToDetailMap.putAll(
                        detailList.stream().collect(Collectors.toMap(RtCfgStatusInfodetailDO::getDid, d -> d)));
            }

            for (RtCfgStatusInfodetailDO detail : rtCfgStatusInfoVO.getRtCfgStatusInfodetail()) {
                DspfStatusModuleitemsubDTO dspfStatusModuleitemsubDTO = dspfStatusModuleitemsubMapper.selectBySid(
                        detail.getSid());
                if (dspfStatusModuleitemsubDTO == null) {
                    continue; // 或记录日志，根据业务需求处理
                }

                if (existingDetailMap.containsKey(detail.getDid())) {
                    // 更新已有明细
                    RtCfgStatusInfodetailDO existingDetail = existingDetailMap.get(detail.getDid());
                    RtCfgStatusInfodetailDO rtCfgStatusInfodetailDO = didToDetailMap.get(detail.getDid());
                    if (rtCfgStatusInfodetailDO == null) {
                        // 处理查不到的情况，可能是并发删除或其他异常
                        continue;
                    }

                    //判断是否进行了修改  然后将修改前的数值存储起来
                    boolean valueChanged = !Objects.equals(rtCfgStatusInfodetailDO.getSelectvaluecode(),
                                                           detail.getSelectvaluecode()) ||
                            !Objects.equals(rtCfgStatusInfodetailDO.getSelectvaluename(), detail.getSelectvaluename());

                    if (valueChanged) {
                        rtCfgStatusInfodetailDO.setOldcode(rtCfgStatusInfodetailDO.getSelectvaluecode());
                        rtCfgStatusInfodetailDO.setOldtext(rtCfgStatusInfodetailDO.getSelectvaluename());
                        rtCfgStatusInfodetailDO.setValuechanged(1);
                    }

                    StringBuilder descriptionSplices = new StringBuilder();
                    descriptionSplices.append(dspfStatusModuleitemsubDTO.getDescrName())
                            .append(":")
                            .append(detail.getSelectvaluename())
                            .append(";");
                    rtCfgStatusInfodetailDO.setDescriptionsplices(descriptionSplices.toString());

                    rtCfgStatusInfodetailDO.setFModifydate(now);
                    rtCfgStatusInfodetailDO.setFModifyuserid(String.valueOf(user.getOid()));
                    rtCfgStatusInfodetailDO.setFModifyusername(user.getName());
                    rtCfgStatusInfodetailDO.setSelectvaluename(detail.getSelectvaluename());
                    rtCfgStatusInfodetailDO.setSelectvaluecode(detail.getSelectvaluecode());

                    detailsToUpdate.add(rtCfgStatusInfodetailDO);
                } else {
                    // 新增明细
                    StringBuilder descriptionSplices = new StringBuilder();
                    descriptionSplices.append(dspfStatusModuleitemsubDTO.getDescrName())
                            .append(":")
                            .append(detail.getSelectvaluename())
                            .append(";");

                    detail.setDescriptionsplices(descriptionSplices.toString());
                    detail.setModuleid(rtCfgStatusInfoVO.getDspfStatusModuleitem().get(0).getModuleId());
                    detail.setDid(String.valueOf(snowflakeIdComponent.getInstance().nextId()));
                    detail.setInfoid(rtCfgStatusInfoDO.getStatusid());
                    detail.setSubtype(dspfStatusModuleitemsubDTO.getSubType());
                    detail.setFDeletemark(0);
                    detail.setFEnabledmark(1);
                    detail.setFCreatedate(now);
                    detail.setFCreateuserid(String.valueOf(user.getOid()));
                    detail.setFCreateusername(user.getName());
                    detailsToInsert.add(detail);
                }
            }


            // 单条更新已有明细
            if (!detailsToUpdate.isEmpty()) {
                int updatedCount = 0;
                for (RtCfgStatusInfodetailDO detail : detailsToUpdate) {
                    int result = rtCfgStatusInfodetailService.updateRtCfgStatusInfodetail(detail);
                    if (result > 0) {
                        updatedCount += result;
                    }
                }
                if (updatedCount <= 0) {
                    throw RTErrorCodeEnum.STATUS_INFO_CONTENT_IS_NULL.getException("明细表更新失败");
                }
            }


            // 批量新增明细
            if (!detailsToInsert.isEmpty()) {
                if (rtCfgStatusInfodetailService.batchRtCfgStatusInfodetail(detailsToInsert) <= 0) {
                    throw RTErrorCodeEnum.STATUS_INFO_CONTENT_IS_NULL.getException("明细表新增失败");
                }
            }

            // 在明细表处理完成后，根据明细表数据更新主表的特定字段

            // 获取当前数据库最新的数据
            List<RtCfgStatusInfodetailDO> latestDetails = rtCfgStatusInfodetailService.selectByInfoId(
                    rtCfgStatusInfoDO.getStatusid());

            // 拼接选中值名称，使用下划线分隔 (例如: a_b_c)
            // 全拼接
            StringBuilder descriptionBuilder = new StringBuilder();
            // 短拼接
            StringBuilder shortDescriptionBuilder = new StringBuilder();

            // 创建一个包含 detail 和对应 dspfStatusModuleitemsubDTO 的列表，用于排序
            List<Map.Entry<RtCfgStatusInfodetailDO, DspfStatusModuleitemsubDTO>> sortedEntries = new ArrayList<>();
            Set<String> processedDetails = new HashSet<>(); // 用于跟踪已处理的detail

            for (RtCfgStatusInfodetailDO detail : latestDetails) {
                if (detail.getSelectvaluename() != null && detail.getSid() != null) {
                    String detailKey = detail.getDid() + "_" + detail.getSid(); // 创建唯一标识
                    if (!processedDetails.contains(detailKey)) {
                        DspfStatusModuleitemsubDTO dspfStatusModuleitemsubDTO = dspfStatusModuleitemsubMapper.selectBySid(
                                detail.getSid());
                        if (dspfStatusModuleitemsubDTO != null) {
                            sortedEntries.add(new AbstractMap.SimpleEntry<>(detail, dspfStatusModuleitemsubDTO));
                            processedDetails.add(detailKey);
                        }
                    }
                }
            }

            // 根据 descriptionsort 字段排序，空值排在最后
            // 如果 descriptionsort 相同，则按照修改时间降序排列（最新的在前）
            // 如果修改时间也相同，则按照创建时间降序排列（最新的在前）
            sortedEntries.sort((entry1, entry2) -> {
                Integer sort1 = entry1.getValue().getDescriptionsort();
                Integer sort2 = entry2.getValue().getDescriptionsort();

                // 先比较 descriptionsort
                int sortCompare = Comparator.nullsLast(Integer::compareTo).compare(sort1, sort2);
                if (sortCompare != 0) {
                    return sortCompare;
                }

                // 如果 descriptionsort 相同，则比较修改时间（降序，最新的在前）
                Date modifyDate1 = entry1.getKey().getFModifydate();
                Date modifyDate2 = entry2.getKey().getFModifydate();
                int modifyDateCompare = Comparator.nullsLast(Date::compareTo).reversed().compare(modifyDate1,
                                                                                                 modifyDate2);
                if (modifyDateCompare != 0) {
                    return modifyDateCompare;
                }

                // 如果修改时间也相同，则比较创建时间（降序，最新的在前）
                Date createDate1 = entry1.getKey().getFCreatedate();
                Date createDate2 = entry2.getKey().getFCreatedate();
                return Comparator.nullsLast(Date::compareTo).reversed().compare(createDate1, createDate2);
            });


            // 用于跟踪已添加的内容，避免重复
            Set<String> addedToDescription = new HashSet<>();
            Set<String> addedToShortDescription = new HashSet<>();

            // 按排序后的顺序进行拼接
            for (Map.Entry<RtCfgStatusInfodetailDO, DspfStatusModuleitemsubDTO> entry : sortedEntries) {
                RtCfgStatusInfodetailDO detail = entry.getKey();
                DspfStatusModuleitemsubDTO dspfStatusModuleitemsubDTO = entry.getValue();

                // 构建长描述内容
                String descriptionContent = dspfStatusModuleitemsubDTO.getDescrName() + detail.getSelectvaluename();
                if (!addedToDescription.contains(descriptionContent)) {
                    if (descriptionBuilder.length() > 0) {
                        descriptionBuilder.append("_");
                    }
                    descriptionBuilder.append(dspfStatusModuleitemsubDTO.getDescrName());
                    descriptionBuilder.append(detail.getSelectvaluename());
                    addedToDescription.add(descriptionContent);
                }

                // 处理短描述（仅当IsDescribe为1时）
                if (dspfStatusModuleitemsubDTO.getIsDescribe() != null && dspfStatusModuleitemsubDTO.getIsDescribe() == 1) {
                    String shortDescriptionContent = dspfStatusModuleitemsubDTO.getShortDescription() + detail.getSelectvaluename();
                    if (!addedToShortDescription.contains(shortDescriptionContent)) {
                        if (shortDescriptionBuilder.length() > 0) {
                            shortDescriptionBuilder.append("_");
                        }
                        shortDescriptionBuilder.append(dspfStatusModuleitemsubDTO.getShortDescription());
                        shortDescriptionBuilder.append(detail.getSelectvaluename());
                        addedToShortDescription.add(shortDescriptionContent);
                    }
                }
            }

            // 更新主表的 短描述 字段
            rtCfgStatusInfoDO.setDescription(shortDescriptionBuilder.toString());
            // 更新主表的长描述字段
            rtCfgStatusInfoDO.setDescriptionsplices(descriptionBuilder.toString());
            if (rtCfgStatusInfoMapper.updateByStatusId(rtCfgStatusInfoDO) <= 0) {
                throw RTErrorCodeEnum.STATUS_INFO_CONTENT_IS_NULL.getException("主表二次更新失败");
            }
            return ResponseResult.success(rtCfgStatusInfoDO, "保存成功!");

        } catch (Exception e) {
            e.printStackTrace();
            throw RTErrorCodeEnum.STATUS_INFO_CONTENT_IS_NULL.getException("保存需求状态信息失败");
        }
    }

    private String getMasterOidByOid(String fatherOid) {
        String masterOid = rtCfgStatusInfoMapper.getMasterOidByOid(fatherOid);
        return masterOid;
    }

    private RtCfgStatusInfoVO handleFileArr(RtCfgStatusInfoVO rtCfgStatusInfoVO) {
        //        RtCfgStatusInfoDO rtCfgStatusInfo = rtCfgStatusInfoVO.getRtCfgStatusInfo();
        //        if (ObjectUtil.isNotEmpty(rtCfgStatusInfo)) {
        //            if (IterUtil.isNotEmpty(rtCfgStatusInfo.getAttachfilesArr())) {
        //                rtCfgStatusInfo.setAttachfiles(JSONUtil.toJsonStr(rtCfgStatusInfo.getAttachfilesArr()));
        //            }
        //            if (IterUtil.isNotEmpty(rtCfgStatusInfo.getRequirementfileArr())) {
        //                rtCfgStatusInfo.setRequirementfile(JSONUtil.toJsonStr(rtCfgStatusInfo.getRequirementfileArr()));
        //            }
        //            if (StrUtil.isNotEmpty(rtCfgStatusInfo.getAttachfiles())) {
        //                rtCfgStatusInfo.setAttachfilesArr(JSONUtil.toList(rtCfgStatusInfo.getAttachfiles(), Map.class));
        //            }
        //            if (StrUtil.isNotEmpty(rtCfgStatusInfo.getRequirementfile())) {
        //                rtCfgStatusInfo.setRequirementfileArr(JSONUtil.toList(rtCfgStatusInfo.getRequirementfile(), Map.class));
        //            }
        //            rtCfgStatusInfoVO.setRtCfgStatusInfo(rtCfgStatusInfo);
        //        }
        return rtCfgStatusInfoVO;
    }


    /**
     * 调用底层方法进行需求状态表新增
     *
     * @param rtCfgStatusInfoVO
     */
    private PdmPartInfoVO savePdmPartInfo(RtCfgStatusInfoVO rtCfgStatusInfoVO) {

        InsertPartDTO insertPartDTO = JSONUtil.toBean(jsonXqzt183, InsertPartDTO.class);
        if (Objects.nonNull(insertPartDTO)) {
            LinkedHashMap<String, List<String>> ibaAttribute = new LinkedHashMap<>();
            ibaAttribute.put("productType", Arrays.asList(rtCfgStatusInfoVO.getRtCfgStatusInfo().getProducttype()));
            ibaAttribute.put("devCode", Arrays.asList(rtCfgStatusInfoVO.getRtCfgStatusInfo().getDevcode()));
            insertPartDTO.setIbaAttribute(ibaAttribute);
            insertPartDTO.setName(rtCfgStatusInfoVO.getRtCfgStatusInfo().getStatustitle());
            insertPartDTO.setDescription(rtCfgStatusInfoVO.getRtCfgStatusInfo().getStatedescription());
            insertPartDTO.setPartNumber(rtCfgStatusInfoVO.getRtCfgStatusInfo().getStatuscode());
            ArgumentUtils.checkArgumentNull(insertPartDTO.getPartView(),
                                            PartBomErrorCodeEnum.EXCEPTION_PARAM_VIEW_ID_IS_EMPTY.getLocaleMessage());
        }
        PdmPartInfoVO partInfoVO = typlmPdmPartService.insertPart(new UploadFileDTO(), new LinkedHashMap<>(),
                                                                  insertPartDTO);
        return partInfoVO;
    }

    @Override
    public ResponseResult getRtCfgStatusInfoDetail(RtCfgStatusInfoVO rtCfgStatusInfoVO) {
        List<DspfStatusModuleitemsubDTO> moduleItemSubList = rtCfgStatusInfoVO.getDspfStatusModuleitemsub();
        if (moduleItemSubList == null || moduleItemSubList.isEmpty()) {
            throw RTErrorCodeEnum.STATUS_INFO_CONTENT_IS_NULL.getException("参数不能为空");
        }
        DspfStatusModuleitemsubDTO dspfStatusModuleitemsubDTO = moduleItemSubList.get(0);
        if (dspfStatusModuleitemsubDTO == null) {
            throw RTErrorCodeEnum.STATUS_INFO_CONTENT_IS_NULL.getException("参数不能为空");
        }

        switch (dspfStatusModuleitemsubDTO.getSubType()) {
            case 1: // 数据字典
                return dataDictionary(rtCfgStatusInfoVO);
            //            case 2: // 物料描述
            //                return materialDescription(rtCfgStatusInfoVO);
            case 3: // 测试要求
                return testingRequirements(rtCfgStatusInfoVO);
            case 4: // 认证要求
                return certificationRequirements(rtCfgStatusInfoVO);
            case 5: // 动力
                return dynamic(rtCfgStatusInfoVO);
            case 6: // 打刻
                return engravedAndEngraved(rtCfgStatusInfoVO);
            case 7: // 定制  目前定制比较特殊 这里并不是获取逻辑 而是用户输入之后 进行规则约束
                return customization(rtCfgStatusInfoVO);
            case 8: // 属性拼接
                return atributeConcatenation(rtCfgStatusInfoVO);
            case 9: // 物料类型
                return partType(rtCfgStatusInfoVO);

            // 以下类型为 表头字段下放  将需求表表头的某些数据 转移至需求状态表中 目前不在前端配置 由后端写死
            case 10: // 客户编码 CRM
                return getClientCodeList(rtCfgStatusInfoVO);
            case 11: // 样机类型 CRM
                return getSysItemDetailList(rtCfgStatusInfoVO);
            case 13: // 客户动力备案型号
                return getClientrecordType(rtCfgStatusInfoVO);
            case 12: //产品用途
                return getCpyt(rtCfgStatusInfoVO);
            default:
                return ResponseResult.fail("", "400", "未知的子类型: ");
        }
    }

    //13 产品用途
    private ResponseResult getCpyt(RtCfgStatusInfoVO rtCfgStatusInfoVO) {
        List<StatusInfoDetailContentVO> collect = new ArrayList<>();
        List<RatoCpytDO> query = ratoCpytService.query(new RatoCpytDO());
        new RatoCpytDO();
        query.stream().forEach(cpytDO -> {
            collect.add(new StatusInfoDetailContentVO(cpytDO.getId(), cpytDO.getSecondaryUsage()));
        });
        return getContentByRule(collect, rtCfgStatusInfoVO);
    }

    //12 客户动力备案型号
    private ResponseResult getClientrecordType(RtCfgStatusInfoVO rtCfgStatusInfoVO) {
        RtCfgStatusInfoDO rtCfgStatusInfo = rtCfgStatusInfoVO.getRtCfgStatusInfo();
        List<RtCfgStatusInfodetailDO> rtCfgStatusInfodetail = rtCfgStatusInfoVO.getRtCfgStatusInfodetail();
        boolean flag1 = false;
        boolean flag = false;
        String cretId = "";
        String devCode = "";
        for (RtCfgStatusInfodetailDO rtCfgStatusInfodetailDO : rtCfgStatusInfodetail) {

            if (rtCfgStatusInfodetailDO.getSubtype() == 4) {
                flag = true;
                //获取认证的id
                cretId = rtCfgStatusInfodetailDO.getSelectvaluecode();
                continue;
            }
            if (rtCfgStatusInfodetailDO.getSubtype() == 5) {
                flag1 = true;
                //获取动力的开发令
                devCode = rtCfgStatusInfodetailDO.getSelectvaluecode();
                continue;
            }
            if (flag1 && flag) {
                break;
            }
        }
        if (!flag && !flag1) {
            throw RTErrorCodeEnum.STATUS_INFO_CONTENT_IS_NULL.getException("认证id或者动力为空，请先填写这些内容");
        }
        CustomerQueryDTO customerQueryDTO = new CustomerQueryDTO();
        //放入认证的id
        customerQueryDTO.setCertid(cretId);
        customerQueryDTO.setDevcode(devCode);
        customerQueryDTO.setCustomcode(rtCfgStatusInfo.getCustomecode());
        List<CustomerPowerRecordModel> list = crmApiService.getCustomerPowerRecordModels(customerQueryDTO);
        List<StatusInfoDetailContentVO> result = new ArrayList<>();
        list.forEach(item -> {
            result.add(new StatusInfoDetailContentVO(item.getKHXH(), item.getKHXH()));
        });
        return getContentByRule(result, rtCfgStatusInfoVO);
    }


    //    // 14 产品类别
    //    private ResponseResult getPlTrees(RtCfgStatusInfoVO rtCfgStatusInfoVO) {
    //        List<Map<String,String>> list = rtCfgMzMapper.queryPartsByTypeAndNum();
    //        List<StatusInfoDetailContentVO> collect = list.stream().map(
    //                item -> new StatusInfoDetailContentVO(item.get("PRODUCTLINE"), item.get("VALUE"))).collect(
    //                Collectors.toList());
    //                return getContentByRule(collect, rtCfgStatusInfoVO);
    //    }

    //11 样机类型
    private ResponseResult getSysItemDetailList(RtCfgStatusInfoVO rtCfgStatusInfoVO) {
        CrmApiResponseVO clientCode = crmApiService.getSysItemDetailList();
        if (clientCode.getCode() == 200) {
            // 使用Hutool的JSON处理方式
            List<cn.hutool.json.JSONObject> rawDataList = (List<cn.hutool.json.JSONObject>) clientCode.getData();
            List<StatusInfoDetailContentVO> collect = rawDataList.stream()
                    .map(jsonObject -> {
                        // 使用Hutool JSONObject的getStr方法
                        String sapClientCode = jsonObject.getStr("F_ItemValue", "");
                        String clientCodeStr = jsonObject.getStr("F_ItemValue", "");
                        return new StatusInfoDetailContentVO(sapClientCode, clientCodeStr);
                    })
                    .collect(Collectors.toList());
            return getContentByRule(collect, rtCfgStatusInfoVO);
        } else {
            throw RTErrorCodeEnum.STATUS_INFO_CONTENT_IS_NULL.getException("获取样机类型失败");
        }
    }

    //10  客户编码
    private ResponseResult getClientCodeList(RtCfgStatusInfoVO rtCfgStatusInfoVO) {
        CrmApiResponseVO clientCode = crmApiService.getClientCodeList(new CrmApiQueryDTO());
        if (clientCode.getCode() == 200) {
            // 使用Hutool的JSON处理方式
            List<cn.hutool.json.JSONObject> rawDataList = (List<cn.hutool.json.JSONObject>) clientCode.getData();
            List<StatusInfoDetailContentVO> collect = rawDataList.stream()
                    .map(jsonObject -> {
                        // 使用Hutool JSONObject的getStr方法
                        String sapClientCode = jsonObject.getStr("clientcode", "");
                        String clientCodeStr = jsonObject.getStr("text", "");
                        return new StatusInfoDetailContentVO(sapClientCode, clientCodeStr);
                    })
                    .collect(Collectors.toList());
            return getContentByRule(collect, rtCfgStatusInfoVO);
        } else {
            throw RTErrorCodeEnum.STATUS_INFO_CONTENT_IS_NULL.getException("获取客户编码列表失败");
        }
    }


    // 9 物料类型
    private ResponseResult partType(RtCfgStatusInfoVO rtCfgStatusInfoVO) {
        DspfStatusModuleitemsubDTO dspfStatusModuleitemsub = getFirstModuleItemSub(rtCfgStatusInfoVO);
        RtCfgStatusInfoDO rtCfgStatusInfo = rtCfgStatusInfoVO.getRtCfgStatusInfo();
        if (dspfStatusModuleitemsub == null || rtCfgStatusInfo == null) {
            throw RTErrorCodeEnum.STATUS_INFO_CONTENT_IS_NULL.getException("参数不能为空");
        }
        if (dspfStatusModuleitemsub.getSourceRange() == null) {
            throw RTErrorCodeEnum.STATUS_INFO_CONTENT_IS_NULL.getException("销售选择范围为空");
        }
        String productType = rtCfgStatusInfo.getProducttype();

        //获取品类的名称

        //存放零部件名称
        List<LikeBomVO> rtCfgBomDOList = new ArrayList<>();
        if (dspfStatusModuleitemsub.getPartsCode().isEmpty()) {
            throw RTErrorCodeEnum.STATUS_INFO_CONTENT_IS_NULL.getException("品类不能为空");
        }
        if (dspfStatusModuleitemsub.getIscode() == null) {
            throw RTErrorCodeEnum.STATUS_INFO_CONTENT_IS_NULL.getException("品类类型不能为空");
        }
        if (dspfStatusModuleitemsub.getIscode() == 0) {
            rtCfgBomDOList = rtCfgStatusInfoMapper.getRtCfgPartByPartNumber(
                    dspfStatusModuleitemsub.getPartsCode(),
                    productType,
                    STATUS_INFO_ENUMERATIONTYPE);
        }
        if (dspfStatusModuleitemsub.getIscode() == 1) {
            rtCfgBomDOList = rtCfgStatusInfoMapper.getRtCfgPartByPartNumber(
                    dspfStatusModuleitemsub.getPartsCode(),
                    productType,
                    STATUS_INFO_OBJECTTYPE);
        }
        if (rtCfgBomDOList == null || rtCfgBomDOList.isEmpty()) {
            return getContentByRule(new ArrayList<StatusInfoDetailContentVO>(), rtCfgStatusInfoVO);
        }
        //获取品类开头的物料编码
        List<String> partNumbers = rtCfgBomDOList.stream()
                .map(LikeBomVO::getPartNumber)
                .collect(Collectors.toList());
        List<StatusInfoDetailContentVO> combinedList = partNumbers.stream()
                .map(partNumber -> new StatusInfoDetailContentVO(partNumber, partNumber))
                .collect(Collectors.toList());

        return getContentByRule(combinedList, rtCfgStatusInfoVO);

    }

    // 7 定制
    private ResponseResult customization(RtCfgStatusInfoVO rtCfgStatusInfoVO) {
        DspfStatusModuleitemsubDTO dspfStatusModuleitemsub = getFirstModuleItemSub(rtCfgStatusInfoVO);
        RtCfgStatusInfoDO rtCfgStatusInfo = rtCfgStatusInfoVO.getRtCfgStatusInfo();
        if (dspfStatusModuleitemsub == null || rtCfgStatusInfo == null) {
            throw RTErrorCodeEnum.COMPLETE_DRAW_ERROR.getException("参数不能为空");
        }


        StatusInfoDetailContentVO rtCfgStatusInfodetailVO = new StatusInfoDetailContentVO(
                rtCfgStatusInfoVO.getCustomizationCode(),
                rtCfgStatusInfoVO.getCustomizationName());
        List<StatusInfoDetailContentVO> rtCfgStatusInfodetailVOList = new ArrayList<>();
        rtCfgStatusInfodetailVOList.add(rtCfgStatusInfodetailVO);
        return getContentByRule(rtCfgStatusInfodetailVOList,
                                rtCfgStatusInfoVO);
    }

    // 打刻 6
    private ResponseResult engravedAndEngraved(RtCfgStatusInfoVO rtCfgStatusInfoVO) {
        DspfStatusModuleitemsubDTO dspfStatusModuleitemsub = getFirstModuleItemSub(rtCfgStatusInfoVO);
        RtCfgStatusInfoDO rtCfgStatusInfo = rtCfgStatusInfoVO.getRtCfgStatusInfo();
        if (dspfStatusModuleitemsub == null || rtCfgStatusInfo == null) {
            throw RTErrorCodeEnum.COMPLETE_DRAW_ERROR.getException("参数不能为空");
        }

        String devcode = rtCfgStatusInfo.getDevcode();
        String producttype = rtCfgStatusInfo.getProducttype();


        if (dspfStatusModuleitemsub.getProductClass() == null) {
            throw RTErrorCodeEnum.COMPLETE_DRAW_ERROR.getException("打刻的终端动力不能为空！");
        }
        List<RTDescribeInformationDO> strings = new ArrayList<>();
        String clientrecordtype = rtCfgStatusInfo.getClientrecordtype();
        // 0动力 1终端
        if (dspfStatusModuleitemsub.getProductClass() == 0) {
            String selectValueCode = null;
            List<RtCfgStatusInfodetailDO> detailList = rtCfgStatusInfoVO.getRtCfgStatusInfodetail();

            // 防止空指针访问
            if (detailList != null && !detailList.isEmpty()) {
                for (RtCfgStatusInfodetailDO item : detailList) {
                    if (item != null && item.getSubtype() != null && item.getSubtype() == 5) {
                        selectValueCode = item.getSelectvaluename();
                        break;
                    }
                }
            }

            if (selectValueCode == null) {
                throw RTErrorCodeEnum.COMPLETE_DRAW_ERROR.getException(
                        "动力内容未填写，需先填写动力内容！");
            }

            if (clientrecordtype == null || clientrecordtype == "") {
                throw RTErrorCodeEnum.COMPLETE_DRAW_ERROR.getException(
                        "客户动力备案型号未填写，需先填写动力内容！");
            }
            strings = rtCfgStatusInfoMapper.selectEngraveByProductType(
                    selectValueCode, clientrecordtype);
        } else if (dspfStatusModuleitemsub.getProductClass() == 1) {

            strings = rtCfgStatusInfoMapper.selectEngraveByProductTypeTwo(
                    producttype);
        }


        List<StatusInfoDetailContentVO> result = new ArrayList<>();
        if (strings != null) {
            // 调试代码 - 查看原始数据
            for (RTDescribeInformationDO info : strings) {
                // 创建列表，包含ROW1_RULE1到ROW5_RULE5的值
                List<String> ruleList = Arrays.asList(
                        info.getRow1Rule1(),
                        info.getRow2Rule1(),
                        info.getRow3Rule1(),
                        info.getRow4Rule1(),
                        info.getRow5Rule1()
                );
                // 过滤掉空值并去除首尾空白
                List<String> filteredRules = ruleList.stream()
                        .filter(Objects::nonNull)
                        .map(String::trim)
                        .filter(s -> !s.isEmpty())
                        .collect(Collectors.toList());
                // 使用 ||| 分隔符拼接成字符串
                String joinedRules = String.join("|||", filteredRules);
                // 创建StatusInfoDetailContentVO对象
                StatusInfoDetailContentVO contentVO = new StatusInfoDetailContentVO(
                        String.valueOf(info.getOids()),
                        joinedRules
                );
                result.add(contentVO);
            }

        }
        return getContentByRule(result, rtCfgStatusInfoVO);

    }

    // 动力 5
    private ResponseResult dynamic(RtCfgStatusInfoVO rtCfgStatusInfoVO) {
        DspfStatusModuleitemsubDTO dspfStatusModuleitemsub = getFirstModuleItemSub(rtCfgStatusInfoVO);
        RtCfgStatusInfoDO rtCfgStatusInfo = rtCfgStatusInfoVO.getRtCfgStatusInfo();
        if (dspfStatusModuleitemsub == null || rtCfgStatusInfo == null) {
            throw RTErrorCodeEnum.COMPLETE_DRAW_ERROR.getException("参数不能为空");
        }
        List<StatusInfoDetailContentVO> statusInfoDetailContentVOS = new ArrayList<>();

        //当动力类型为无需动力的时候 只能选择无
        if (rtCfgStatusInfo.getPowertype() != null && rtCfgStatusInfo.getPowertype() == 30) {
            return getContentByRule(statusInfoDetailContentVOS, rtCfgStatusInfoVO);
        }
        if (dspfStatusModuleitemsub.getSourceRange() == null) {
            throw RTErrorCodeEnum.COMPLETE_DRAW_ERROR.getException("销售选择范围为空");
        }
        String producttype = rtCfgStatusInfo.getProducttype();
        String devcode = rtCfgStatusInfo.getDevcode();
        switch (dspfStatusModuleitemsub.getSourceRange()) {
            case 1: // 同机型
                List<String> partNumbers = rtCfgStatusInfoMapper.selectPartNumberByDevCode(
                        devcode);
                for (String partNumber : partNumbers) {
                    PartDO partDO = typlmPdmPartService.queryLastPartDoByPartNumber(partNumber);
                    // 获取BOM结构树
                    PartBomTreeByFilterVO bomTreeVO = commonService.queryChildParts(
                            partNumber,
                            partDO.getOid().toString(),
                            "Design",
                            Boolean.FALSE,
                            null,
                            "N",
                            Boolean.TRUE
                    );
                    List<PartBomTree> partBomTreeList = bomTreeVO.getPartBomTreeList();
                    // 替换整个 selectedCode 区域的代码为以下优化版本：
                    List<StatusInfoDetailContentVO> levelOneMatches = new ArrayList<>();
                    List<StatusInfoDetailContentVO> levelZeroMatches = new ArrayList<>();

                    // 首先收集所有符合条件的level=1的项目
                    partBomTreeList.forEach(partBomTree -> {
                        if ("EBOM号".equals(partBomTree.getTypeName()) && "1".equals(partBomTree.getLevel())) {
                            StatusInfoDetailContentVO statusInfoDetailContentVO = rtCfgStatusInfoMapper.selectdevCodeAndProductTypeByoid(
                                    partBomTree.getPartoid());
                            if (statusInfoDetailContentVO != null &&
                                    statusInfoDetailContentVO.getSelectValueCode() != null &&
                                    (statusInfoDetailContentVO.getSelectValueCode().startsWith("Z") ||
                                            statusInfoDetailContentVO.getSelectValueCode().startsWith("T") ||
                                            statusInfoDetailContentVO.getSelectValueCode().startsWith("M"))) {

                                levelOneMatches.add(statusInfoDetailContentVO);
                            }
                        }
                    });
                    // 将匹配的结果添加到最终列表中
                    statusInfoDetailContentVOS.addAll(levelOneMatches.isEmpty() ? levelZeroMatches : levelOneMatches);
                }
                return getContentByRule(statusInfoDetailContentVOS, rtCfgStatusInfoVO);
            case 0: // 同BOM
                //                if (rtCfgStatusInfo.getRefermbomcode() != null && StrUtil.isNotBlank(
                //                        rtCfgStatusInfo.getRefermbomcode())) {
                //                    PartDO partDO = typlmPdmPartService.queryLastPartDoByPartNumber(rtCfgStatusInfo.getRefermbomcode());
                //                    // 获取BOM结构树
                //                    PartBomTreeByFilterVO bomTreeVO = commonService.queryChildParts(
                //                            rtCfgStatusInfo.getRefermbomcode(),
                //                            partDO.getOid().toString(),
                //                            "Design",
                //                            Boolean.FALSE,
                //                            null,
                //                            "N",
                //                            Boolean.TRUE
                //                    );
                //                    List<PartBomTree> partBomTreeList = bomTreeVO.getPartBomTreeList();
                //                    partBomTreeList.forEach(partBomTree -> {
                //                        if (partBomTree.getLevel() != "0") {
                //                            StatusInfoDetailContentVO statusInfoDetailContentVO = rtCfgStatusInfoMapper.selectdevCodeAndProductTypeByoid(
                //                                    partBomTree.getPartoid());
                //                            statusInfoDetailContentVOS.add(statusInfoDetailContentVO);
                //                        }
                //                    });
                //                } else
                if (rtCfgStatusInfo.getEbomcode() != null && StrUtil.isNotBlank(rtCfgStatusInfo.getEbomcode())) {
                    PartDO partDO = typlmPdmPartService.queryLastPartDoByPartNumber(rtCfgStatusInfo.getEbomcode());
                    // 获取BOM结构树
                    PartBomTreeByFilterVO bomTreeVO = commonService.queryChildParts(
                            rtCfgStatusInfo.getEbomcode(),
                            partDO.getOid().toString(),
                            "Design",
                            Boolean.FALSE,
                            null,
                            "N",
                            Boolean.TRUE
                    );
                    List<PartBomTree> partBomTreeList = bomTreeVO.getPartBomTreeList();
                    partBomTreeList.forEach(partBomTree -> {
                        if ("EBOM号".equals(partBomTree.getTypeName()) && "1".equals(partBomTree.getLevel())) {
                            StatusInfoDetailContentVO statusInfoDetailContentVO = rtCfgStatusInfoMapper.selectdevCodeAndProductTypeByoid(
                                    partBomTree.getPartoid());
                            statusInfoDetailContentVOS.add(statusInfoDetailContentVO);
                        }
                    });
                }
                return getContentByRule(statusInfoDetailContentVOS, rtCfgStatusInfoVO);
            case 2: // 无限制
                List<ModelAndProductTypeVO> modelAndProductTypeVOS = rtCfgStatusInfoMapper.selectDynamicByProductType();
                // 检查集合是否为空
                if (modelAndProductTypeVOS == null || modelAndProductTypeVOS.isEmpty()) {
                    return getContentByRule(statusInfoDetailContentVOS, rtCfgStatusInfoVO);
                }

                // 转换数据并在拼接过程中检查空值
                List<StatusInfoDetailContentVO> convertedList = new ArrayList<>();
                for (ModelAndProductTypeVO vo : modelAndProductTypeVOS) {
                    // 检查devCode是否为空
                    if (vo.getDevCode() == null || vo.getDevCode().isEmpty()) {
                        continue;
                    }
                    // 检查productType是否为空
                    if (vo.getProductType() == null || vo.getProductType().isEmpty()) {
                        continue;
                    }
                    String devCode = vo.getDevCode();
                    String concatenated = vo.getProductType();
                    convertedList.add(new StatusInfoDetailContentVO(devCode, concatenated));
                }

                statusInfoDetailContentVOS.addAll(convertedList);
                return getContentByRule(statusInfoDetailContentVOS, rtCfgStatusInfoVO);
        }
        return null;
    }


    // 认证要求 4
    private ResponseResult certificationRequirements(RtCfgStatusInfoVO rtCfgStatusInfoVO) {
        DspfStatusModuleitemsubDTO dspfStatusModuleitemsub = getFirstModuleItemSub(rtCfgStatusInfoVO);
        RtCfgStatusInfoDO rtCfgStatusInfo = rtCfgStatusInfoVO.getRtCfgStatusInfo();
        if (dspfStatusModuleitemsub == null || rtCfgStatusInfo == null) {
            throw RTErrorCodeEnum.COMPLETE_DRAW_ERROR.getException("参数不能为空");
        }
        if (dspfStatusModuleitemsub.getSourceRange() == null) {
            throw RTErrorCodeEnum.COMPLETE_DRAW_ERROR.getException("销售选择范围为空");
        }
        switch (dspfStatusModuleitemsub.getSourceRange()) {
            case 1: // 同机型
                return cretSameProductType(rtCfgStatusInfoVO, 4);
            case 0: // 同BOM
                return cretHandleSameBom(rtCfgStatusInfoVO, 4);
            case 2: // 无限制
                return cretAll(rtCfgStatusInfoVO, 4);
            default:
                throw RTErrorCodeEnum.COMPLETE_DRAW_ERROR.getException("未知的销售取值范围");
        }
    }

    // 物料描述 2
    //    private ResponseResult materialDescription(RtCfgStatusInfoVO rtCfgStatusInfoVO) {
    //        DspfStatusModuleitemsubDTO dspfStatusModuleitemsub = getFirstModuleItemSub(rtCfgStatusInfoVO);
    //        RtCfgStatusInfoDO rtCfgStatusInfo = rtCfgStatusInfoVO.getRtCfgStatusInfo();
    //        if (dspfStatusModuleitemsub == null || rtCfgStatusInfo == null) {
    //            return ResponseResult.fail("", "500", "参数不能为空");
    //        }
    //        if (dspfStatusModuleitemsub.getSourceRange()==null){
    //            return ResponseResult.fail("", "500", "销售选择范围为空！");
    //        }
    //        switch (dspfStatusModuleitemsub.getSourceRange()) {
    //            case 1: // 同机型
    //                return handleSameProductType(rtCfgStatusInfoVO, 2);
    //            case 0: // 同BOM
    //                return handleSameBom(rtCfgStatusInfoVO);
    //            default:
    //                return ResponseResult.fail("", "400", "未知的销售取值范围: ");
    //        }
    //    }

    // 测试要求 3
    private ResponseResult testingRequirements(RtCfgStatusInfoVO rtCfgStatusInfoVO) {
        DspfStatusModuleitemsubDTO dspfStatusModuleitemsub = getFirstModuleItemSub(rtCfgStatusInfoVO);
        RtCfgStatusInfoDO rtCfgStatusInfo = rtCfgStatusInfoVO.getRtCfgStatusInfo();
        if (dspfStatusModuleitemsub == null || rtCfgStatusInfo == null) {
            throw RTErrorCodeEnum.COMPLETE_DRAW_ERROR.getException("参数不能为空");
        }
        if (rtCfgStatusInfoVO == null) {
            throw RTErrorCodeEnum.COMPLETE_DRAW_ERROR.getException("参数不能为空");
        }
        if (dspfStatusModuleitemsub.getSourceRange() == null) {
            throw RTErrorCodeEnum.COMPLETE_DRAW_ERROR.getException("销售选择范围为空");
        }
        List<StatusInfoDetailContentVO> statusInfoList = new ArrayList<>();
        String devcode = rtCfgStatusInfo.getDevcode();
        String productType = "";
        switch (dspfStatusModuleitemsub.getSourceRange()) {
            case 1: // 同机型
                if (dspfStatusModuleitemsub.getProductClass() == 0) {
                    List<RtCfgStatusInfodetailDO> detailList = rtCfgStatusInfoVO.getRtCfgStatusInfodetail();
                    // 防止空指针访问
                    if (detailList != null && !detailList.isEmpty()) {
                        for (RtCfgStatusInfodetailDO item : detailList) {
                            if (item != null && item.getSubtype() == 5) {
                                productType = item.getSelectvaluename();
                                break;
                            }
                        }
                    }
                    if (productType == null || productType == "") {
                        throw RTErrorCodeEnum.COMPLETE_DRAW_ERROR.getException("请先填写动力机型");
                    }
                } else if (dspfStatusModuleitemsub.getProductClass() == 1) {
                    productType = rtCfgStatusInfo.getProducttype();
                }

                //        //通过机型获取开发令
                String newDevCode = rtCfgStatusInfoMapper.selectDevCodeByProductType(productType);
                // 通过机型查找EBOM
                List<String> partNumbers = rtCfgStatusInfoMapper.selectPartNumberByDevCode(newDevCode);
                //获取EBOM/成品码上的认证要求
                for (String partNumber : partNumbers) {
                    PartDO partDO = typlmPdmPartService.queryLastPartDoByPartNumber(partNumber);
                    // 获取BOM结构树
                    PartBomTreeByFilterVO bomTreeVO = commonService.queryChildParts(
                            partNumber,
                            partDO.getOid().toString(),
                            "Design",
                            Boolean.FALSE,
                            null,
                            "N",
                            Boolean.TRUE
                    );
                    List<PartBomTree> partBomTreeList = bomTreeVO.getPartBomTreeList();
                    partBomTreeList.forEach(partBomTree -> {
                        if (partBomTree.getLevel() == "0" && partBomTree.getTypeName().equals("EBOM号")) {
                            // 通过扩展属性的内部名称 查询认证要求的id
                            Map<String, List<AttributeVO>> attrValueByOidAndKeys =
                                    typlmAttributeValueService.getIbaAttrValueByOidAndKeys(
                                            Collections.singletonList(partDO.getOid()),
                                            TableTypeConstrant.TY_PART_OTYPE,
                                            Collections.singletonList("TestRequire"));
                            // 获取认证要求的certname值（加强空值检查）
                            String attributeValuex = null;
                            List<AttributeVO> attrList = attrValueByOidAndKeys.get(partBomTree.getPartoid());
                            if (attrList != null && !attrList.isEmpty() && attrList.get(0) != null) {
                                attributeValuex = attrList.get(0).getAttributeValuex();
                            }
                            //通过测试要求 查询测试要求底表
                            List<StatusInfoDetailContentVO> list = rtCfgStatusInfoMapper.selectTestByRequirements(
                                    attributeValuex);
                            statusInfoList.addAll(list);
                        }
                    });
                }
                return getContentByRule(statusInfoList, rtCfgStatusInfoVO);
            case 0: // 同BOM
                String ebomcode = rtCfgStatusInfo.getEbomcode();
                if (StrUtil.isBlank(ebomcode)) {
                    throw RTErrorCodeEnum.COMPLETE_DRAW_ERROR.getException("参考EBOM号为空！");
                }
                //获取EBOM/成品码上的认证要求

                PartDO partDO = typlmPdmPartService.queryLastPartDoByPartNumber(ebomcode);
                // 获取BOM结构树
                PartBomTreeByFilterVO bomTreeVO = commonService.queryChildParts(
                        ebomcode,
                        partDO.getOid().toString(),
                        "Design",
                        Boolean.FALSE,
                        null,
                        "N",
                        Boolean.TRUE
                );
                List<PartBomTree> partBomTreeList = bomTreeVO.getPartBomTreeList();
                partBomTreeList.forEach(partBomTree -> {
                    if (partBomTree.getLevel() == "0" && partBomTree.getTypeName().equals("EBOM号")) {
                        // 通过扩展属性的内部名称 查询认证要求的id
                        Map<String, List<AttributeVO>> attrValueByOidAndKeys =
                                typlmAttributeValueService.getIbaAttrValueByOidAndKeys(
                                        Collections.singletonList(partDO.getOid()),
                                        TableTypeConstrant.TY_PART_OTYPE,
                                        Collections.singletonList("TestRequire"));
                        // 获取测试要求的值（加强空值检查）
                        String attributeValuex = null;
                        List<AttributeVO> attrList = attrValueByOidAndKeys.get(partBomTree.getPartoid());
                        if (attrList != null && !attrList.isEmpty() && attrList.get(0) != null) {
                            attributeValuex = attrList.get(0).getAttributeValuex();
                        }
                        //通过测试要求 查询测试要求底表
                        List<StatusInfoDetailContentVO> list = rtCfgStatusInfoMapper.selectTestByRequirements(
                                attributeValuex);
                        statusInfoList.addAll(list);
                    }
                });
                return getContentByRule(statusInfoList, rtCfgStatusInfoVO);
            case 2: // 无限制
                if (dspfStatusModuleitemsub.getProductClass() == null) {
                    throw RTErrorCodeEnum.COMPLETE_DRAW_ERROR.getException("测试要求的终端动力不能为空！");
                }
                List<StatusInfoDetailContentVO> strings = new ArrayList<>();
                // 0动力 1终端
                if (dspfStatusModuleitemsub.getProductClass() == 0) {
                    String selectValueCode = null;
                    List<RtCfgStatusInfodetailDO> detailList = rtCfgStatusInfoVO.getRtCfgStatusInfodetail();

                    // 防止空指针访问
                    if (detailList != null && !detailList.isEmpty()) {
                        for (RtCfgStatusInfodetailDO item : detailList) {
                            if (item != null && item.getSubtype() == 5) {
                                selectValueCode = item.getSelectvaluename();
                                break;
                            }
                        }
                    }

                    if (selectValueCode == null) {
                        throw RTErrorCodeEnum.COMPLETE_DRAW_ERROR.getException(
                                "动力内容未填写，需先填写动力内容！");
                    }

                    String devCode = rtCfgStatusInfoMapper.selectDevCodeByProductType(selectValueCode);
                    strings = rtTestRequirementsService.selectStatusInfoDetailContentVO(devCode);
                } else if (dspfStatusModuleitemsub.getProductClass() == 1) {
                    strings = rtTestRequirementsService.selectStatusInfoDetailContentVO(devcode);
                }
                return getContentByRule(strings, rtCfgStatusInfoVO);
            default:
                throw RTErrorCodeEnum.COMPLETE_DRAW_ERROR.getException("未知销售选择范围");
        }
    }

    // 数据字典 1
    private ResponseResult dataDictionary(RtCfgStatusInfoVO rtCfgStatusInfoVO) {
        //获取当前行的内容
        DspfStatusModuleitemsubDTO dspfStatusModuleitemsub = getFirstModuleItemSub(rtCfgStatusInfoVO);
        RtCfgStatusInfoDO rtCfgStatusInfo = rtCfgStatusInfoVO.getRtCfgStatusInfo();
        if (dspfStatusModuleitemsub == null || rtCfgStatusInfo == null) {
            throw RTErrorCodeEnum.COMPLETE_DRAW_ERROR.getException("参数不能为空");
        }
        //        if (dspfStatusModuleitemsub.getSourceRange() == null) {
        //            return ResponseResult.fail("", "500", "销售选择范围为空！");
        //        }
        //        switch (dspfStatusModuleitemsub.getSourceRange()) {
        //            case 1: // 同机型
        //                return handleSameProductType(rtCfgStatusInfoVO, 1);
        //            case 0: // 同BOM
        //                return handleSameBom(rtCfgStatusInfoVO);
        //            case 2: // 无限制
        IdentifierEntity identifierEntity = new IdentifierEntity();
        try {
            String dataItemCode = dspfStatusModuleitemsub.getDataItemCode();
            BigInteger bigInteger = rtCfgStatusInfoMapper.selectDataItemByNname(dataItemCode);
            identifierEntity.setOid(bigInteger);
        } catch (NumberFormatException e) {
            throw RTErrorCodeEnum.COMPLETE_DRAW_ERROR.getException("数据字典获取失败，请检查数据字典数据");
        }
        List<EnumerationItemHandleVO> aTrue = typlmEnumerationItemService.queryEnumerationItemByDefOid(
                        identifierEntity)
                .stream()
                .filter(item -> item.getState().equals("true"))
                .collect(Collectors.toList());
        List<StatusInfoDetailContentVO> strings = aTrue.stream()
                .map(item -> new StatusInfoDetailContentVO(item.getInternalName(), item.getDisplayName()))
                .collect(Collectors.toList());
        return getContentByRule(strings, rtCfgStatusInfoVO);
        //            default:
        //                return ResponseResult.fail("", "400", "未知的销售取值范围: ");
        //        }

    }

    /**
     *  8 属性拼接
     * @param rtCfgStatusInfoVO
     * @return
     */
    private ResponseResult atributeConcatenation(RtCfgStatusInfoVO rtCfgStatusInfoVO) {
        DspfStatusModuleitemsubDTO dspfStatusModuleitemsub = getFirstModuleItemSub(rtCfgStatusInfoVO);
        RtCfgStatusInfoDO rtCfgStatusInfo = rtCfgStatusInfoVO.getRtCfgStatusInfo();
        if (dspfStatusModuleitemsub == null || rtCfgStatusInfo == null) {
            throw RTErrorCodeEnum.COMPLETE_DRAW_ERROR.getException("参数不能为空");
        }
        //通过内容 获取动力机型
        String productType = "";
        if (dspfStatusModuleitemsub.getProductClass() == 0) {
            List<RtCfgStatusInfodetailDO> detailList = rtCfgStatusInfoVO.getRtCfgStatusInfodetail();
            if (detailList != null && !detailList.isEmpty()) {
                for (RtCfgStatusInfodetailDO item : detailList) {
                    if (item != null && item.getSubtype() == 5) {
                        productType = item.getSelectvaluename();
                        break;
                    }
                }
            }
            if (productType == null || productType.isEmpty()) {
                throw RTErrorCodeEnum.COMPLETE_DRAW_ERROR.getException("请先填写动力机型");
            }
        } else if (dspfStatusModuleitemsub.getProductClass() == 1) {
            productType = rtCfgStatusInfo.getProducttype();
        }

        String devcode = rtCfgStatusInfoMapper.selectDevCodeByProductType(productType);
        List<String> partNumbers = rtCfgStatusInfoMapper.selectPartNumberByDevCode(devcode);

        List<String> attributeIdList = new ArrayList<>();
        List<StatusInfoDetailContentVO> combinedList = new ArrayList<>();
        List<LikeBomVO> rtCfgBomDOList = new ArrayList<>();

        if (dspfStatusModuleitemsub.getPartsCode() != null) {
            attributeIdList = Arrays.asList(dspfStatusModuleitemsub.getDescrCode().split(","));
            if (dspfStatusModuleitemsub.getPartsCode().isEmpty()) {
                throw RTErrorCodeEnum.COMPLETE_DRAW_ERROR.getException("品类不能为空");
            }
            if (dspfStatusModuleitemsub.getIscode() == null) {
                throw RTErrorCodeEnum.COMPLETE_DRAW_ERROR.getException("品类类型不能为空");
            }

            if (dspfStatusModuleitemsub.getIscode() == 0) {
                rtCfgBomDOList = rtCfgStatusInfoMapper.getRtCfgPartByPartNumberTwo(
                        dspfStatusModuleitemsub.getPartsCode(), devcode, "图样代号");
            } else if (dspfStatusModuleitemsub.getIscode() == 1) {
                rtCfgBomDOList = rtCfgStatusInfoMapper.getRtCfgPartByPartNumberTwo(
                        dspfStatusModuleitemsub.getPartsCode(), devcode, "物料码");
            }

            List<ResultEntityVO> partList = new ArrayList<>();
            for (LikeBomVO likeBomVO : rtCfgBomDOList) {
                SearchConditionDTO dto = new SearchConditionDTO();
                dto.setTypeInthid(TableTypeConstrant.TY_PART_OTYPE);
                dto.setClassificationOid(new BigInteger(likeBomVO.getOid()));
                dto.setNeedThumbnailFile(false);
                dto.setPageSize(9999);
                dto.setPageNum(1);
                List<ResultEntityVO> resultEntityVOS = typlmClassifySearchService.queryByCondition(dto);
                partList.addAll(resultEntityVOS);
            }

            for (ResultEntityVO item : partList) {
                String partNumber = item.getObjectNumber();
                List<IbaAttributeValueVO> ibaAttributeValueVOS = rtCfgStatusInfoMapper.selectIbaBypartNumbers(
                        partNumber, attributeIdList, null);
                if (ibaAttributeValueVOS.isEmpty()) {
                    continue;
                }

                // 1. 构建属性映射表（复用，同时服务于code和value）
                Map<String, IbaAttributeValueVO> attrMap = ibaAttributeValueVOS.stream()
                        .filter(Objects::nonNull)
                        .filter(attr -> attr.getNname() != null)
                        .collect(Collectors.toMap(IbaAttributeValueVO::getNname, attr -> attr, (existing, replacement) -> existing));

                // 2. 拼接code（保持原有逻辑，顺序正确）
                List<String> codeParts = attributeIdList.stream()
                        .map(attrId -> {
                            IbaAttributeValueVO attr = attrMap.get(attrId);
                            if (attr != null) {
                                String value = attr.getValueex() != null ? attr.getValueex() : attr.getValuee();
                                return value != null && !value.trim().isEmpty() ? value : null;
                            }
                            return null;
                        })
                        .filter(Objects::nonNull)
                        .collect(Collectors.toList());
                String code = String.join("_", codeParts);

                // 3. 拼接value（关键修改：按attributeIdList顺序，而非查询结果顺序）
                List<String> valueParts = attributeIdList.stream()
                        .map(attrId -> {
                            IbaAttributeValueVO attr = attrMap.get(attrId);
                            if (attr == null) {
                                return null; // 跳过不存在的属性
                            }
                            // 校验必要字段（避免空指针和无效数据）
                            if (attr.getName() == null || attr.getName().trim().isEmpty()
                                    || attr.getNname() == null || attr.getNname().trim().isEmpty()
                                    || (attr.getValuee() == null && attr.getValueex() == null)) {
                                return null;
                            }
                            // 调用原有处理方法（保持显示格式不变）
                            return processAttributeValue(attr.getName(), attr.getNname(), attr.getValuee(), attr.getValueex());
                        })
                        .filter(Objects::nonNull)
                        .filter(result -> !result.trim().isEmpty())
                        .collect(Collectors.toList());
                String value = String.join("_", valueParts);

                // 避免添加空数据（可选，根据业务需求）
                if (!code.isEmpty() && !value.isEmpty()) {
                    combinedList.add(new StatusInfoDetailContentVO(code, value));
                }
            }
        }
        return getContentByRule(combinedList, rtCfgStatusInfoVO);
    }

    /**
     * @param name 枚举项的显示名称
     * @param nname 枚举项的内部名称
     * @param valuee 枚举值的内部名称
     * @param valueex 枚举值的内部名称
     * @return
     */
    private String processAttributeValue(String name, String nname, String valuee, String valueex) {
        if(nname.contains("color")){
            nname = nname != null && nname.contains("color;;;") ? nname.substring(nname.lastIndexOf(";;;") + 3) : nname;
        }

        // 查询枚举定义OID
        BigInteger oid = dspfStatusModuleitemsubMapper.selectEnumerationByName(nname);

        // 处理可能的空值情况
        if (oid == null) {
            return name + valuee; // 根据业务需求决定是否抛异常或默认值
        }

        // 通过OID查询枚举项
        IdentifierEntity identifierEntity = new IdentifierEntity();
        identifierEntity.setOid(oid);

        List<EnumerationItemHandleVO> enumerationItems = this.typlmEnumerationItemService.queryEnumerationItemByDefOid(
                identifierEntity);

        // 处理查询结果为空的情况
        if (enumerationItems == null || enumerationItems.isEmpty()) {
            return "";
        }

        // 查找第一个匹配的枚举项并构建显示名称
        return enumerationItems.stream()
                .filter(item -> item != null && valueex.equals(item.getName()))
                .findFirst()
                .map(item -> name + item.getDisplayName())
                .orElse("");
    }


    //获取第一个 DspfStatusModuleitemsubDTO
    private DspfStatusModuleitemsubDTO getFirstModuleItemSub(RtCfgStatusInfoVO rtCfgStatusInfoVO) {
        List<DspfStatusModuleitemsubDTO> moduleItemSubList = rtCfgStatusInfoVO.getDspfStatusModuleitemsub();
        if (moduleItemSubList == null || moduleItemSubList.isEmpty()) {
            return null;
        }
        return moduleItemSubList.get(0);
    }

    //处理同机型逻辑
    private ResponseResult handleSameProductType(RtCfgStatusInfoVO rtCfgStatusInfoVO, int subType) {
        //获取机型
        RtCfgStatusInfoDO rtCfgStatusInfo = rtCfgStatusInfoVO.getRtCfgStatusInfo();
        String productType = rtCfgStatusInfo.getProducttype();
        //通过机型和类型 在需求状态表内容里面过滤出来已经有的数据
        List<StatusInfoDetailContentVO> strings = rtCfgStatusInfodetailService.selectBySubtypeAndProductType(subType,
                                                                                                             productType);
        if (subType == 6) {
            // 过滤掉已停用的数据
            strings = strings.stream()
                    .filter(statusInfoDetailContentVO -> !isDataDisabled(
                            statusInfoDetailContentVO.getSelectValueCode()))
                    .collect(Collectors.toList());

        }
        //过滤空值 重复数据 并且验证规则校验
        return getContentByRule(strings, rtCfgStatusInfoVO);
    }


    /**
     * 检查指定编码的数据是否已经被停用
     *
     * @param code 编码
     * @return true表示已停用，false表示未停用
     */
    private boolean isDataDisabled(String code) {
        // 假设这里有一个方法可以根据编码查询到对应数据的状态
        // 示例：从数据库查询状态，假设status=0表示启用，status=1表示停用
        // 示例SQL: SELECT status FROM some_table WHERE code = ?

        // 这里应替换成实际的业务逻辑
        Integer status = rtCfgStatusInfoMapper.inspectStopFlag(code);

        // 如果status为null，默认认为未停用
        return status != null && status == 1;
    }


    /**
     * 提取同BOM处理逻辑为通用方法
     */

    private ResponseResult handleSameBom(RtCfgStatusInfoVO rtCfgStatusInfoVO, int subType) {
        RtCfgStatusInfoDO rtCfgStatusInfo = rtCfgStatusInfoVO.getRtCfgStatusInfo();
        DspfStatusModuleitemsubDTO dspfStatusModuleitemsub = getFirstModuleItemSub(rtCfgStatusInfoVO);
        if (rtCfgStatusInfo == null || dspfStatusModuleitemsub == null) {
            throw RTErrorCodeEnum.COMPLETE_DRAW_ERROR.getException("参数不能为空");
        }

        // 获取参考成品码
        String productcode = rtCfgStatusInfo.getRefermbomcode();
        if (StringUtils.isNotBlank(productcode)) {
            //通过成品码获取状态ID
            String statusid = rtCfgStatusInfoMapper.getStatusIdByProductCode(productcode);
            if (StringUtils.isNotBlank(statusid)) {
                //通过 需求状态表的id拿到状态内容
                List<StatusInfoDetailContentVO> statusInfoDetailContentVOS = rtCfgStatusInfodetailMapper.selectCodeAndValueByStatusId(
                        statusid, subType);
                //打刻
                if (subType == 6) {
                    // 过滤掉已停用的数据
                    statusInfoDetailContentVOS = statusInfoDetailContentVOS.stream()
                            .filter(statusInfoDetailContentVO -> !isDataDisabled(
                                    statusInfoDetailContentVO.getSelectValueCode()))
                            .collect(Collectors.toList());

                }
                return getContentByRule(statusInfoDetailContentVOS,
                                        rtCfgStatusInfoVO);
            }
        }

        // 获取参考EBOM码
        String ebomcode = rtCfgStatusInfo.getEbomcode();
        if (StringUtils.isNotBlank(ebomcode)) {
            List<String> statusIds = rtCfgStatusInfoMapper.selectByEBomCode(ebomcode);
            if (!statusIds.isEmpty()) {
                List<StatusInfoDetailContentVO> allStatusInfoDetails = new ArrayList<>();
                for (String statusId : statusIds) {
                    List<StatusInfoDetailContentVO> statusInfoDetailContentVOS = rtCfgStatusInfodetailMapper.selectCodeAndValueByStatusId(
                            statusId, dspfStatusModuleitemsub.getSubType());
                    allStatusInfoDetails.addAll(statusInfoDetailContentVOS);
                }
                return getContentByRule(allStatusInfoDetails, rtCfgStatusInfoVO);
            }
        }
        throw RTErrorCodeEnum.COMPLETE_DRAW_ERROR.getException("参考成品码为空值");
    }


    /**
     * 处理认证同机型逻辑
     *
     * @param rtCfgStatusInfoVO
     * @param subType
     * @return 获取逻辑：
     * 先通过动力或者终端 获取开发令  然后通过开发令 获取EBOM和成品BON
     */
    private ResponseResult cretSameProductType(RtCfgStatusInfoVO rtCfgStatusInfoVO, int subType) {
        // 获取机型
        RtCfgStatusInfoDO rtCfgStatusInfo = rtCfgStatusInfoVO.getRtCfgStatusInfo();
        DspfStatusModuleitemsubDTO firstModuleItemSub = getFirstModuleItemSub(rtCfgStatusInfoVO);

        if (rtCfgStatusInfoVO == null) {
            throw RTErrorCodeEnum.COMPLETE_DRAW_ERROR.getException("参数不能为空");
        }
        String productType = "";
        if (firstModuleItemSub.getProductClass() == 0) {
            List<RtCfgStatusInfodetailDO> detailList = rtCfgStatusInfoVO.getRtCfgStatusInfodetail();
            // 防止空指针访问
            if (detailList != null && !detailList.isEmpty()) {
                for (RtCfgStatusInfodetailDO item : detailList) {
                    if (item != null && item.getSubtype() == 5) {
                        productType = item.getSelectvaluename();
                        break;
                    }
                }
            }
            if (productType == null || productType == "") {
                throw RTErrorCodeEnum.COMPLETE_DRAW_ERROR.getException("请先填写动力机型");
            }
        } else if (firstModuleItemSub.getProductClass() == 1) {
            productType = rtCfgStatusInfo.getProducttype();
        }
        List<StatusInfoDetailContentVO> statusInfoList = new ArrayList<>();
        //        //通过机型获取开发令
        String newDevCode = rtCfgStatusInfoMapper.selectDevCodeByProductType(productType);
        // 通过机型查找EBOM
        List<String> partNumbers = rtCfgStatusInfoMapper.selectPartNumberByDevCode(newDevCode);
        //获取EBOM/成品码上的认证要求
        for (String partNumber : partNumbers) {
            PartDO partDO = typlmPdmPartService.queryLastPartDoByPartNumber(partNumber);
            // 获取BOM结构树
            PartBomTreeByFilterVO bomTreeVO = commonService.queryChildParts(
                    partNumber,
                    partDO.getOid().toString(),
                    "Design",
                    Boolean.FALSE,
                    null,
                    "N",
                    Boolean.TRUE
            );
            List<PartBomTree> partBomTreeList = bomTreeVO.getPartBomTreeList();
            partBomTreeList.forEach(partBomTree -> {
                //                if(partBomTree.getLevel() == "0" && partBomTree.getTypeName().equals("成品码")){
                //                    // 通过扩展属性的内部名称 查询认证要求的id
                //                    Map<String, List<AttributeVO>> attrValueByOidAndKeys =
                //                            typlmAttributeValueService.getIbaAttrValueByOidAndKeys(
                //                                    Collections.singletonList(partDO.getOid()),
                //                                    TableTypeConstrant.TY_PART_OTYPE,
                //                                    Collections.singletonList("00036"));
                //                    //获取认证要求的id值
                //                    String attributeValuex = attrValueByOidAndKeys.get(partBomTree.getPartoid()).get(0)
                //                            .getAttributeValuex();
                //                    //通过id查询有效的认证要求
                //                    String certname = rtCfgStatusInfoMapper.selectCombcertByoid(attributeValuex);
                //                    statusInfoList.add( new StatusInfoDetailContentVO (attributeValuex,certname));
                //
                //                }else
                if (partBomTree.getLevel() == "0" && partBomTree.getTypeName().equals("EBOM号")) {
                    // 通过扩展属性的内部名称 查询认证要求的id
                    Map<String, List<AttributeVO>> attrValueByOidAndKeys =
                            typlmAttributeValueService.getIbaAttrValueByOidAndKeys(
                                    Collections.singletonList(partDO.getOid()),
                                    TableTypeConstrant.TY_PART_OTYPE,
                                    Collections.singletonList("CertificationRequire"));
                    // 获取认证要求的certname值（加强空值检查）
                    String attributeValuex = null;
                    List<AttributeVO> attrList = attrValueByOidAndKeys.get(partBomTree.getPartoid());
                    if (attrList != null && !attrList.isEmpty() && attrList.get(0) != null) {
                        attributeValuex = attrList.get(0).getAttributeValuex();
                    }

                    // 安全拆分并转换为List
                    List<String> splitList = new ArrayList<>();
                    if (attributeValuex != null && !attributeValuex.isEmpty()) {
                        splitList = Arrays.asList(attributeValuex.split(";"));
                    }
                    //通过certname查询有效的认证要求
                    List<StatusInfoDetailContentVO> list = rtCfgStatusInfoMapper.selectCombcertByCertname(splitList);
                    statusInfoList.addAll(list);
                }
            });
        }
        // 获取销售国家信息
        String saletocountry = rtCfgStatusInfo.getSaletocountry();
        if (saletocountry == null || StrUtil.isBlank(saletocountry)) {
            throw RTErrorCodeEnum.COMPLETE_DRAW_ERROR.getException("终端销售国为空，请先填写");
        }

        // 拆分国家列表
        List<String> saletocountryList = Arrays.asList(saletocountry.split(","));

        // 根据国家和认证信息过滤，取交集
        List<StatusInfoDetailContentVO> result = filterCertificationByCountries(statusInfoList, saletocountryList);

        // 过滤空值、重复数据并验证规则
        return getContentByRule(result, rtCfgStatusInfoVO);
    }

    // 认证要求提取同BOM处理逻辑
    private ResponseResult cretHandleSameBom(RtCfgStatusInfoVO rtCfgStatusInfoVO, int subType) {
        // 获取机型
        RtCfgStatusInfoDO rtCfgStatusInfo = rtCfgStatusInfoVO.getRtCfgStatusInfo();
        if (rtCfgStatusInfoVO == null) {
            throw RTErrorCodeEnum.COMPLETE_DRAW_ERROR.getException("参数不能为空");
        }
        // 获取销售国家信息
        String saletocountry = rtCfgStatusInfo.getSaletocountry();
        if (saletocountry == null || StrUtil.isBlank(saletocountry)) {
            throw RTErrorCodeEnum.COMPLETE_DRAW_ERROR.getException("终端销售国为空，请先填写");
        }
        // 通过参考成品码 或者参考EBOM 获取认证
        String partNumber = "";
        if (rtCfgStatusInfo.getEbomcode() != null && !rtCfgStatusInfo.getEbomcode().equals("")) {
            partNumber = rtCfgStatusInfo.getEbomcode();
        }
        if (StrUtil.isBlank(partNumber)) {
            throw RTErrorCodeEnum.COMPLETE_DRAW_ERROR.getException("参考EBOM为空！！");
        }
        List<StatusInfoDetailContentVO> statusInfoList = new ArrayList<>();

        PartDO partDO = typlmPdmPartService.queryLastPartDoByPartNumber(partNumber);
        // 获取BOM结构树
        PartBomTreeByFilterVO bomTreeVO = commonService.queryChildParts(
                partNumber,
                partDO.getOid().toString(),
                "Design",
                Boolean.FALSE,
                null,
                "N",
                Boolean.TRUE
        );
        List<PartBomTree> partBomTreeList = bomTreeVO.getPartBomTreeList();
        partBomTreeList.forEach(partBomTree -> {
            if (partBomTree.getLevel() == "0" && partBomTree.getTypeName().equals("EBOM号")) {
                // 通过扩展属性的内部名称 查询认证要求的id
                Map<String, List<AttributeVO>> attrValueByOidAndKeys =
                        typlmAttributeValueService.getIbaAttrValueByOidAndKeys(
                                Collections.singletonList(partDO.getOid()),
                                TableTypeConstrant.TY_PART_OTYPE,
                                Collections.singletonList("CertificationRequire"));
                // 获取认证要求的certname值（加强空值检查）
                String attributeValuex = null;
                List<AttributeVO> attrList = attrValueByOidAndKeys.get(partBomTree.getPartoid());
                if (attrList != null && !attrList.isEmpty() && attrList.get(0) != null) {
                    attributeValuex = attrList.get(0).getAttributeValuex();
                }

                // 安全拆分并转换为List
                List<String> splitList = new ArrayList<>();
                if (attributeValuex != null && !attributeValuex.isEmpty()) {
                    splitList = Arrays.asList(attributeValuex.split(";"));
                }
                //通过certname查询有效的认证要求
                List<StatusInfoDetailContentVO> list = rtCfgStatusInfoMapper.selectCombcertByCertname(splitList);
                statusInfoList.addAll(list);
            }
        });


        // 拆分国家列表
        List<String> saletocountryList = Arrays.asList(saletocountry.split(","));

        // 根据国家和认证信息过滤，取并集
        List<StatusInfoDetailContentVO> result = filterCertificationByCountries(statusInfoList, saletocountryList);

        // 过滤空值、重复数据并验证规则
        return getContentByRule(result, rtCfgStatusInfoVO);
    }

    // 认证要求提取所有认证信息
    private ResponseResult cretAll(RtCfgStatusInfoVO rtCfgStatusInfoVO, int subType) {
        RtCfgStatusInfoDO rtCfgStatusInfo = rtCfgStatusInfoVO.getRtCfgStatusInfo();
        DspfStatusModuleitemsubDTO dspfStatusModuleitemsub = getFirstModuleItemSub(rtCfgStatusInfoVO);

        if (rtCfgStatusInfo == null || dspfStatusModuleitemsub == null) {
            throw RTErrorCodeEnum.COMPLETE_DRAW_ERROR.getException("参数不能为空");
        }
        // 获取销售国家信息
        String saletocountry = rtCfgStatusInfo.getSaletocountry();
        if (saletocountry == null) {
            throw RTErrorCodeEnum.COMPLETE_DRAW_ERROR.getException("终端销售国为空，请先填写");
        }

        String productType = "";
        if (dspfStatusModuleitemsub.getProductClass() == 0) {
            List<RtCfgStatusInfodetailDO> detailList = rtCfgStatusInfoVO.getRtCfgStatusInfodetail();
            // 防止空指针访问
            if (detailList != null && !detailList.isEmpty()) {
                for (RtCfgStatusInfodetailDO item : detailList) {
                    if (item != null && item.getSubtype() == 5) {
                        productType = item.getSelectvaluename();
                        break;
                    }
                }
            }
            if (productType == null || productType == "") {
                throw RTErrorCodeEnum.COMPLETE_DRAW_ERROR.getException("请先填写动力机型");
            }
        } else if (dspfStatusModuleitemsub.getProductClass() == 1) {
            productType = rtCfgStatusInfo.getProducttype();
        }
        //通过产品类型查询开发令
        String devCode = rtCfgStatusInfoMapper.selectDevCodeByProductType(productType);
        // 通过开发令获取产品线（取开发令的第一个字符）
        String productLine = "";
        if (devCode != null && !devCode.isEmpty()) {
            // 提取开发令的前1个字符作为产品线标识
            int endIndex = Math.min(devCode.length(), 1);
            productLine = devCode.substring(0, endIndex);
        }


        // 拆分国家列表
        List<String> saletocountryList = Arrays.asList(saletocountry.split(","));

        // 查询所有国家和产品线对应的认证信息
        List<StatusInfoDetailContentVO> statusInfoDetailContentVOS = new ArrayList<>();
        for (String country : saletocountryList) {
            //通过产品线和销售国家获取基础认证中的信息
            List<StatusInfoDetailContentVO> collection = rtCfgStatusInfoMapper.selectcretAllBycountryAndDevCode(
                    productLine, country);
            //通过这些基础认证的信息 查询组合认证
            for (StatusInfoDetailContentVO item : collection) {
                //拆分认证信息
                List<String> availablecertList = Arrays.asList(item.getSelectValueCode().split("\\s+"));
                List<StatusInfoDetailContentVO> statusInfoDetailContentVOS1 = rtCfgStatusInfoMapper.selectAllCertByBaseCert(
                        availablecertList, country);
                statusInfoDetailContentVOS.addAll(statusInfoDetailContentVOS1);
            }
        }

        // 过滤空值、重复数据并验证规则
        return getContentByRule(statusInfoDetailContentVOS, rtCfgStatusInfoVO);
    }

    /**
     * 根据国家列表过滤认证信息，计算所有国家的并集
     *
     * @param certifications 认证信息列表
     * @param countries 国家列表
     * @return 过滤后的认证信息列表（并集）
     */
    private List<StatusInfoDetailContentVO> filterCertificationByCountries(
            List<StatusInfoDetailContentVO> certifications, List<String> countries) {

        List<StatusInfoDetailContentVO> result = new ArrayList<>();

        // 参数校验
        if (certifications == null || certifications.isEmpty() ||
                countries == null || countries.isEmpty()) {
            return result;
        }

        // 计算所有国家查询结果的并集
        Set<String> uniqueCodes = new HashSet<>(); // 用于去重

        for (String country : countries) {
            // 查询当前国家对应的认证信息
            for (StatusInfoDetailContentVO certification : certifications) {
                List<StatusInfoDetailContentVO> countryCertifications =
                        rtCfgStatusInfoMapper.selectCretBySaletocountry(
                                certification.getSelectValueCode(), country);

                if (countryCertifications != null && !countryCertifications.isEmpty()) {
                    // 添加到结果中，同时去重
                    for (StatusInfoDetailContentVO cert : countryCertifications) {
                        if (!uniqueCodes.contains(cert.getSelectValueCode())) {
                            uniqueCodes.add(cert.getSelectValueCode());
                            result.add(cert);
                        }
                    }
                }
            }
        }

        // 如果结果为空，使用"其他国家"作为备选方案
        if (result.isEmpty()) {
            String fallbackCountry = "其他国家";
            for (StatusInfoDetailContentVO certification : certifications) {
                List<StatusInfoDetailContentVO> countryCertifications =
                        rtCfgStatusInfoMapper.selectCretBySaletocountry(
                                certification.getSelectValueCode(), fallbackCountry);

                if (countryCertifications != null && !countryCertifications.isEmpty()) {
                    for (StatusInfoDetailContentVO cert : countryCertifications) {
                        if (!uniqueCodes.contains(cert.getSelectValueCode())) {
                            uniqueCodes.add(cert.getSelectValueCode());
                            result.add(cert);
                        }
                    }
                }
            }
        }

        return result;
    }


    @Override
    public ResponseResult getPartsByClassOid(SearchConditionDTO conditionDTO, String devCode) {
        try {
            // 设置分页参数，如果未提供则使用默认值
            int pageLimit = (conditionDTO.getPageSize() > 0) ? conditionDTO.getPageSize() : 10;
            int pageOffset = (conditionDTO.getPageNum() > 0) ? conditionDTO.getPageNum() : 1;

            // 设置查询条件
            conditionDTO.setNeedThumbnailFile(true);
            conditionDTO.setTypeInthid(MODEL_IBA_TYPE);

            // 执行查询获取所有数据
            SearchConditionDTO conditionDTO1 = new SearchConditionDTO();
            conditionDTO1.setClassificationOid(conditionDTO.getClassificationOid());
            conditionDTO1.setPageSize(1500);
            conditionDTO1.setPageNum(1);
            // 设置查询条件
            conditionDTO1.setNeedThumbnailFile(true);
            conditionDTO1.setTypeInthid(MODEL_IBA_TYPE);
            PageInfo<ResultEntityVO> resultEntityVOPageInfo = typlmClassifySearchService.queryByConditionByPage(
                    conditionDTO1);
            List<ResultEntityVO> allResults = typlmClassifySearchService.queryByCondition(conditionDTO);
            if (allResults == null) {
                allResults = new ArrayList<>();
            }
            // 手动分页
            Long total = (long) resultEntityVOPageInfo.getList().size();
            if (StringUtils.isNotBlank(devCode)) {
                allResults = resultEntityVOPageInfo.getList().stream()
                        .filter(result -> result.getObjectNumber().contains(devCode))
                        .collect(Collectors.toList());
                total = (long) allResults.size();
            }


            // 提取零部件编号
            List<String> collect = allResults.stream()
                    .map(ResultEntityVO::getObjectNumber)
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());

            // 获取零部件扩展属性数据
            Map<String, List<TyIbaDataDTO>> partDetailsVOList = new HashMap<>();
            try {
                for (String partNumber : collect) {
                    List<TyIbaDataDTO> ibaMapByNumber = dspfMbomBomMapper.getIbaMapByNumber(partNumber);
                    if (ibaMapByNumber != null && !ibaMapByNumber.isEmpty()) {
                        partDetailsVOList.put(partNumber, ibaMapByNumber);
                    }
                }
            } catch (Exception e) {
                throw RTErrorCodeEnum.COMPLETE_DRAW_ERROR.getException("获取零部件扩展属性数据异常");
            }

            // 构建分页结果
            Map<String, Object> result = new HashMap<>();
            result.put("data", partDetailsVOList);
            result.put("total", total);
            result.put("pageNumber", pageOffset);
            result.put("pageSize", pageLimit);

            return ResponseResult.success(result, "");
        } catch (Exception e) {
            throw RTErrorCodeEnum.COMPLETE_DRAW_ERROR.getException("查询零部件异常");
        }
    }


    @Override
    public ResponseResult getProductType() {

        return ResponseResult.success(rtCfgStatusInfoMapper.getProductType(STATUS_INFO_PARTTYPE, MODEL_IBA_TYPE), "");
    }

    @Override
    public ResponseResult getProductCodeList(List<StatusInfoDescriptionVO> dto, Integer pageNumber, Integer pageSize) {
        try {
            // 参数校验：确保 dto 不为空且至少包含一个元素
            if (CollectionUtils.isEmpty(dto)) {
                throw RTErrorCodeEnum.COMPLETE_DRAW_ERROR.getException("参数错误");
            }

            // 分页参数处理
            int pageLimit = (pageSize != null && pageSize > 0) ? pageSize : 10;
            int pageOffset = (pageNumber != null && pageNumber > 0) ? pageNumber : 1;

            long offset = (pageOffset - 1L) * pageLimit;
            long limit = pageLimit;

            // 查询数据 - 传递整个 dto 列表
            List<ProductCodeAndDescriptionVO> partNumbers = rtCfgStatusInfoMapper.selectProductCodeList(
                    dto, offset, limit);

            long total = rtCfgStatusInfoMapper.countProductCode(dto);

            // 构建分页响应（即使为空也要返回结构）
            Map<String, Object> result = new HashMap<>();
            result.put("data", partNumbers != null ? partNumbers : Collections.emptyList());
            result.put("total", total);
            result.put("pageNumber", pageOffset);
            result.put("pageSize", pageLimit);

            return ResponseResult.success(result, "");
        } catch (Exception e) {
            throw RTErrorCodeEnum.COMPLETE_DRAW_ERROR.getException("查询成品码异常");
        }
    }


    @Override
    public ResponseResult getDefaultTemplate() {
        return ResponseResult.success(
                rtCfgStatusInfoMapper.getDefaultTemplate(STATUS_INFO_REFTYPE, MODEL_IBA_TYPE, "默认模板"), "");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult deleteRtCfgStatusInfo(String[] infoIds) {
        if (infoIds == null || infoIds.length == 0) {
            throw RTErrorCodeEnum.COMPLETE_DRAW_ERROR.getException("传入的参数为空");
        }
        Long l = rtCfgStatusInfoMapper.deleteBatchByInfoIds(infoIds);
        //调用底层需求状态表高级删除方法
        this.deleteXqztInfo(infoIds);

        if (l <= 0) {
            throw RTErrorCodeEnum.COMPLETE_DRAW_ERROR.getException("删除rtCfgStatusInfo记录失败");
        }
        List<RtCfgStatusInfodetailDO> rtCfgStatusInfodetailDOS = rtCfgStatusInfodetailMapper.selectBatchByInfoIds(
                infoIds);
        if (!rtCfgStatusInfodetailDOS.isEmpty()) {
            Long l1 = rtCfgStatusInfodetailMapper.deleteBatchByInfoIds(infoIds);
            if (l1 <= 0) {
                throw RTErrorCodeEnum.COMPLETE_DRAW_ERROR.getException("删除rtCfgStatusInfodetail记录失败");
            }
        }
        return ResponseResult.success("", "200");
    }


    /**
     * 调用底层高级删除需求状态表方法
     *
     * @param infoIds
     */
    private void deleteXqztInfo(String[] infoIds) {
        List<String> list = Arrays.asList(infoIds);
        if (IterUtil.isNotEmpty(list)) {
            list.stream().forEach(i -> {
                RtCfgStatusInfoDO rtCfgStatusInfoDO = rtCfgStatusInfoMapper.selectByStatusId(i);
                if (ObjectUtil.isNotEmpty(rtCfgStatusInfoDO)) {
                    DeleteDTO deleteDTO = new DeleteDTO();
                    deleteDTO.setDeleteType("allRevisions");
                    deleteDTO.setOid(rtCfgStatusInfoDO.getOid());
                    deleteDTO.setOtype(rtCfgStatusInfoDO.getOtype());
                    this.doCommonDelete(Arrays.asList(deleteDTO));
                }
            });
        }
    }

    private com.ty.basic.response.ResponseResult doCommonDelete(List<DeleteDTO> list) {
        try {
            if (!org.springframework.util.CollectionUtils.isEmpty(list)) {
                list.forEach((vo) -> {
                    typlmLogger.info(new CTyEntityBaseDO(vo.getOid(), vo.getOtype()), LogEventEnum.DELETE_OBJECT);
                });
            }
        } catch (Exception var4) {
            log.error("记录审计日志===>> ", var4);
        }

        try {
            if (!org.springframework.util.CollectionUtils.isEmpty(list)) {
                commonDeleteService.productCommonDelete(list);
            }

            return com.ty.basic.response.ResponseResult.success();
        } catch (Exception var5) {
            if (!org.springframework.util.CollectionUtils.isEmpty(list)) {
                if (list.size() == 1) {
                    DeleteDTO deleteDTO = (DeleteDTO) list.get(0);
                    typlmLogger.errorInfo(new CTyEntityBaseDO(deleteDTO.getOid(), deleteDTO.getOtype()),
                                          LogEventEnum.DELETE_OBJECT, var5);
                } else {
                    typlmLogger.errorInfo(LogEventEnum.DELETE_OBJECT, new AuditLogDO(), var5);
                }
            }

            throw var5;
        }
    }

    //    /**
    //     * 根据规则校验 来过滤下拉值
    //     *
    //     * @param list
    //     * @param rtCfgStatusInfoVO
    //     * @return
    //     */
    //    public List<StatusInfoDetailContentVO> getContentByRule(List<StatusInfoDetailContentVO> list,
    //                                                            RtCfgStatusInfoVO rtCfgStatusInfoVO) {
    //        List<RtCfgTemplatecontentConstraintsDO> rtCfgTemplatecontentConstraintsDOList = rtCfgTemplatecontentConstraintsMapper.selectBySid(
    //                new BigInteger(rtCfgStatusInfoVO.getDspfStatusModuleitemsub().get(0).getSid()));
    //        list.add(new StatusInfoDetailContentVO("/", "无"));
    //        list.stream().distinct().collect(Collectors.toList());
    //        for (RtCfgTemplatecontentConstraintsDO rtCfgTemplatecontentConstraintsDO : rtCfgTemplatecontentConstraintsDOList) {
    //            //获取规则表达式
    //            String ruleContent = rtCfgTemplatecontentConstraintsDO.getRuleContent();
    //            //获取前置对象oid的集合
    //            String preconditionsOids = rtCfgTemplatecontentConstraintsDO.getPreconditionsOids();
    //            //拆分前置对象的oid
    //            String[] sids = preconditionsOids.split(",");
    //            //获取结论关系
    //            Integer conclusionRelationship = rtCfgTemplatecontentConstraintsDO.getConclusionRelationship();
    //            //获取结果内容
    //            String conclusionValue = rtCfgTemplatecontentConstraintsDO.getConclusionValue();
    //            //获取各个前置对象当前实际填写的内容
    //            List<RtCfgStatusInfodetailDO> rtCfgStatusInfodetail = rtCfgStatusInfoVO.getRtCfgStatusInfodetail();
    ////            // 构建sid到selectvaluename的映射，sid不能为空，但selectvaluename允许为空
    ////            Map<String, String> stringStringMap = rtCfgStatusInfodetail.stream()
    ////                    .filter(d -> d.getSid() != null)  // 确保sid不为null（Map的key不能为null）
    ////                    .collect(Collectors.toMap(
    ////                            RtCfgStatusInfodetailDO::getSid,           // key: sid（非null）
    ////                            RtCfgStatusInfodetailDO::getSelectvaluename, // value: selectvaluename（允许为null）
    ////                            (existing, replacement) -> existing         // 处理重复key，保留第一个值
    ////                    ));
    //            // 替换原有的 Collectors.toMap 代码块（第1112-1119行）
    //            // 原代码有问题，替换为以下代码：
    //            Map<String, String> stringStringMap = new HashMap<>();
    //            for (RtCfgStatusInfodetailDO detail : rtCfgStatusInfodetail) {
    //                if (detail.getSid() != null) {
    //                    for ( String sid:sids){
    //                        if (sid.equals(detail.getSid())){
    //                            stringStringMap.put(detail.getSid(), detail.getSelectvaluename());
    //                        }
    //                    }
    //                }
    //            }
    //            // 修改后代码
    //            if (stringStringMap == null || stringStringMap.isEmpty()) {
    //                // 当没有任何前置对象内容填写时，找出第一个相关的前置对象并提示用户填写
    //                if (sids.length > 0) {
    //                    DspfStatusModuleitemsubDTO dspfStatusModuleitemsubDTO = dspfStatusModuleitemsubMapper.selectBySid(sids[0]);
    //                    String message = "本内容涉及到规则约束，请先填写：" +
    //                            (dspfStatusModuleitemsubDTO != null ? dspfStatusModuleitemsubDTO.getDescrName() : "未知内容") +
    //                            "的内容!";
    //                    throw RTErrorCodeEnum.STATUS_INFO_CONTENT_IS_NULL.getException(message);
    //                }
    //                // 如果无法获取具体信息，则给出通用提示
    //                throw RTErrorCodeEnum.STATUS_INFO_CONTENT_IS_NULL.getException(
    //                        "本内容涉及到规则约束，请先填写前置内容!");
    //                //当规则较严重没有相关的配置后，就直接原数据返回
    ////                return list.stream().distinct().collect(Collectors.toList());
    //            }
    //
    //            // 修改后的安全代码：
    //            if (stringStringMap != null) {
    //                for (Map.Entry<String, String> entry : stringStringMap.entrySet()) {
    //                    String key = entry.getKey();
    //                    Object valueObj = entry.getValue(); // 使用Object类型接收值
    //
    //                    // 检查值是否为null
    //                    if (valueObj == null) {
    //                        DspfStatusModuleitemsubDTO dspfStatusModuleitemsubDTO = dspfStatusModuleitemsubMapper.selectBySid(key);
    //                        String message = "本内容涉及到规则约束，请先填写：" +
    //                                (dspfStatusModuleitemsubDTO != null ? dspfStatusModuleitemsubDTO.getDescrName() : "未知内容") +
    //                                "的内容!";
    //                        throw RTErrorCodeEnum.STATUS_INFO_CONTENT_IS_NULL.getException(message);
    //                    }
    //
    //                    // 如果值不是String类型，尝试安全转换
    //                    String value;
    //                    if (valueObj instanceof String) {
    //                        value = (String) valueObj;
    //                    } else {
    //                        // 处理NClob或其他非String类型
    //                        try {
    //                            // 尝试调用toString方法获取值
    //                            value = valueObj.toString();
    //                        } catch (Exception e) {
    //                            // 如果转换失败，视为空值处理
    //                            DspfStatusModuleitemsubDTO dspfStatusModuleitemsubDTO = dspfStatusModuleitemsubMapper.selectBySid(key);
    //                            String message = "本内容涉及到规则约束，请先填写：" +
    //                                    (dspfStatusModuleitemsubDTO != null ? dspfStatusModuleitemsubDTO.getDescrName() : "未知内容") +
    //                                    "的内容!";
    //                            throw RTErrorCodeEnum.STATUS_INFO_CONTENT_IS_NULL.getException(message);
    //                        }
    //                    }
    //
    //                    // 检查转换后的值是否为空字符串
    //                    if (value == null || value.isEmpty()) {
    //                        DspfStatusModuleitemsubDTO dspfStatusModuleitemsubDTO = dspfStatusModuleitemsubMapper.selectBySid(key);
    //                        String message = "本内容涉及到规则约束，请先填写：" +
    //                                (dspfStatusModuleitemsubDTO != null ? dspfStatusModuleitemsubDTO.getDescrName() : "未知内容") +
    //                                "的内容!";
    //                        throw RTErrorCodeEnum.STATUS_INFO_CONTENT_IS_NULL.getException(message);
    //                    }
    //                }
    //            }
    //            boolean b = rtCfgTemplatecontentConstraintsServiceImpl.evaluateDynamicCondition(stringStringMap,
    //                                                                                            ruleContent);
    //            if (b) {
    //                switch (conclusionRelationship) {
    //                    case 1://包含
    //                        list.removeIf(s -> !conclusionValue.equals(s.getSelectValueName()) && !"/".equals(s.getSelectValueCode()));
    //                        break;
    //
    //                    case 2: //不包含
    //                        list.removeIf(s -> !conclusionValue.equals(s.getSelectValueName()) && !"/".equals(s.getSelectValueCode()));
    //                        break;
    //
    //                    case 3: //等于
    //                        list.removeIf(s -> !conclusionValue.equals(s.getSelectValueName()) && !"/".equals(s.getSelectValueCode()));
    //                        break;
    //
    //                    case 4: //不等于
    //                        list.removeIf(s -> !conclusionValue.equals(s.getSelectValueName()) && !"/".equals(s.getSelectValueCode()));
    //                        break;
    //
    //                    default:
    //                        // 处理未知的conclusionRelationship值
    //                        break;
    //                }
    //            }
    //        }
    ////
    ////        // 添加"无"选项并去重
    ////        list.add(new StatusInfoDetailContentVO("/", "无"));
    //        return list.stream()
    //                .filter(Objects::nonNull)  // 过滤掉null值
    //                .filter(item -> StringUtils.isNotBlank(item.getSelectValueCode()) ||
    //                        StringUtils.isNotBlank(item.getSelectValueName()))  // 过滤掉code和name都为空的项
    //                .distinct()  // 去重
    //                .collect(Collectors.toList());
    //    }

    /**
     * 根据规则校验 来过滤下拉值
     *
     * @param list
     * @param rtCfgStatusInfoVO
     * @return
     */
    public ResponseResult getContentByRule(List<StatusInfoDetailContentVO> list,
                                           RtCfgStatusInfoVO rtCfgStatusInfoVO) {
        List<RtCfgTemplatecontentConstraintsDO> rtCfgTemplatecontentConstraintsDOList = rtCfgTemplatecontentConstraintsMapper.selectBySid(
                rtCfgStatusInfoVO.getDspfStatusModuleitemsub().get(0).getSid());
        if (list == null) {
            list = new ArrayList<>();
        }
        // 去重并赋值
        list = list.stream().distinct().collect(Collectors.toList());
        String sql = "";
        for (RtCfgTemplatecontentConstraintsDO rtCfgTemplatecontentConstraintsDO : rtCfgTemplatecontentConstraintsDOList) {
            // 获取规则表达式
            String ruleContent = rtCfgTemplatecontentConstraintsDO.getRuleContent();
            // 获取前置对象oid的集合
            String preconditionsOids = rtCfgTemplatecontentConstraintsDO.getPreconditionsOids();
            // 拆分前置对象的oid
            String[] sids = preconditionsOids.split(",");
            Set<String> sidSet = Arrays.stream(sids).collect(Collectors.toSet());

            // 获取结论关系
            Integer conclusionRelationship = rtCfgTemplatecontentConstraintsDO.getConclusionRelationship();
            // 获取结果内容
            String conclusionValue = rtCfgTemplatecontentConstraintsDO.getConclusionValue();

            // 获取各个前置对象当前实际填写的内容
            List<RtCfgStatusInfodetailDO> rtCfgStatusInfodetail = rtCfgStatusInfoVO.getRtCfgStatusInfodetail();

            // 构建sid到selectvaluename的映射
            Map<String, String> stringStringMap = new HashMap<>();
            for (RtCfgStatusInfodetailDO detail : rtCfgStatusInfodetail) {
                if (detail.getSid() != null && sidSet.contains(detail.getSid())) {
                    stringStringMap.put(detail.getSid(), detail.getSelectvaluename());
                }
            }

            // 检查是否有前置对象未填写
            if (stringStringMap.isEmpty()) {
                handleMissingPrecondition(sids.length > 0 ? sids[0] : null);
            }

            // 检查每个前置对象的值是否为空
            for (Map.Entry<String, String> entry : stringStringMap.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                if (value == null || value.isEmpty()) {
                    handleMissingPrecondition(key);
                }
            }

            boolean b = rtCfgTemplatecontentConstraintsServiceImpl.evaluateDynamicCondition(stringStringMap,
                                                                                            ruleContent);

            if (b) {
                String[] conclusionValues = conclusionValue.split("[;；]");

                switch (conclusionRelationship) {
                    case 1: // 包含
                        sql = "本条内容涉及规则校验：选择/输入的内容需要包含" + conclusionValue;
                        list.removeIf(s -> shouldRemoveItem(s, conclusionValues, conclusionRelationship));
                        break;
                    case 2: // 不包含
                        sql = "本条内容涉及规则校验：选择/输入的内容不能包含" + conclusionValue;
                        list.removeIf(s -> shouldRemoveItem(s, conclusionValues, conclusionRelationship));
                        break;
                    case 3: // 等于
                        sql = "本条内容涉及规则校验：选择/输入的内容需要等于" + conclusionValue;
                        list.removeIf(s -> shouldRemoveItem(s, conclusionValues, conclusionRelationship));
                        break;
                    case 4: // 不等于
                        sql = "本条内容涉及规则校验：选择/输入的内容不能等于" + conclusionValue;
                        list.removeIf(s -> shouldRemoveItem(s, conclusionValues, conclusionRelationship));
                        break;
                    default:
                        break;
                }
            }
        }
        if (rtCfgStatusInfoVO.getDspfStatusModuleitemsub().get(0).getSubType() != 4
                && rtCfgStatusInfoVO.getDspfStatusModuleitemsub().get(0).getSubType() != 3
                && rtCfgStatusInfoVO.getDspfStatusModuleitemsub().get(0).getSubType() != 7
                && rtCfgStatusInfoVO.getDspfStatusModuleitemsub().get(0).getSubType() != 1
        ) {
            // 添加"无"选项并去重
            list.add(new StatusInfoDetailContentVO("/", "无"));
        }
        List<StatusInfoDetailContentVO> collect = list.stream()
                .filter(Objects::nonNull)
                .filter(item -> StringUtils.isNotBlank(item.getSelectValueCode()) ||
                        StringUtils.isNotBlank(item.getSelectValueName()))
                .distinct()
                .collect(Collectors.toList());
        if (sql != "" && rtCfgStatusInfoVO.getDspfStatusModuleitemsub().get(0).getSubType() == 7) {
            throw RTErrorCodeEnum.STATUS_INFO_CONTENT_IS_NULL.getException(sql);
        } else {
            return ResponseResult.success(collect, "");
        }
    }

    //用来处理规则校验内容处理逻辑
    private boolean shouldRemoveItem(StatusInfoDetailContentVO s, String[] conclusionValues,
                                     Integer conclusionRelationship) {
        switch (conclusionRelationship) {
            case 1: // 包含
                for (String value : conclusionValues) {
                    if (s.getSelectValueName().contains(value.trim())) {
                        return false; // 包含任意一个值，保留
                    }
                }
                return !"/".equals(s.getSelectValueCode());

            case 2: // 不包含
                for (String value : conclusionValues) {
                    if (s.getSelectValueName().contains(value.trim())) {
                        return !"/".equals(s.getSelectValueCode()); // 包含任意一个值则移除
                    }
                }
                return false;

            case 3: // 等于
                for (String value : conclusionValues) {
                    if (value.trim().equals(s.getSelectValueName())) {
                        return false; // 等于任意一个值，保留
                    }
                }
                return !"/".equals(s.getSelectValueCode());

            case 4: // 不等于
                for (String value : conclusionValues) {
                    if (value.trim().equals(s.getSelectValueName())) {
                        return !"/".equals(s.getSelectValueCode()); // 等于任意一个值则移除
                    }
                }
                return false;

            default:
                return false;
        }
    }

    // 提取异常处理逻辑为私有方法
    private void handleMissingPrecondition(String sid) {
        if (sid != null) {
            DspfStatusModuleitemsubDTO dspfStatusModuleitemsubDTO = dspfStatusModuleitemsubMapper.selectBySid(sid);
            String message = "本内容涉及到规则约束，请先填写：" +
                    (dspfStatusModuleitemsubDTO != null ? dspfStatusModuleitemsubDTO.getDescrName() : "未知内容") +
                    "的内容!";
            throw RTErrorCodeEnum.STATUS_INFO_CONTENT_IS_NULL.getException(message);
        } else {
            throw RTErrorCodeEnum.STATUS_INFO_CONTENT_IS_NULL.getException("本内容涉及到规则约束，请先填写前置内容!");
        }
    }


    @Override
    public ResponseResult getInstantiatedObject() {
        //        SearchClassificationDTO searchClassificationDTO = new SearchClassificationDTO();
        //        searchClassificationDTO.setOid(new BigInteger("0"));
        //        searchClassificationDTO.setTypeInthid(TableTypeConstrant.TY_PART_OTYPE);
        //        searchClassificationDTO.setRootOid(new BigInteger("720076410394099712"));
        //        List<String> oidList = new ArrayList<>();
        //        //获取该分类下的所有子集分类的oid
        //        List<BigInteger> partOids = rtEngraveMapper.selectIbaAttr("产品型谱");


        return null;
    }

    @Override
    public ResponseResult getRtCfgStatusInfoCode(String code) {
        //todo 暂时用时间代替，后续更改
        String statusCode = code + DateUtil.format(DateUtil.date(), "yyyyMMddHHmmssSSS");
        Map<Object, Object> objectObjectMap = new HashMap<>();
        objectObjectMap.put("statusCode", statusCode);
        return ResponseResult.success(objectObjectMap, "获取成功");
    }

    @Override
    public ResponseResult customization(RtCfgBOMAndStatusInfoDTO rtCfgBOMAndStatusInfoDTO) {
        RtCfgStatusDTO rtCfgStatusDTO = new RtCfgStatusDTO();
        rtCfgStatusDTO.setStatusCode(rtCfgBOMAndStatusInfoDTO.getStatusCode());
        RtCfgStatusInfoDO rtCfgStatusInfoDO = rtCfgStatusInfoMapper.selectByStatusCode(rtCfgStatusDTO);
        List<RtCfgStatusInfodetailDO> objects = new ArrayList<>();
        List<RtCfgStatusInfodetailDO> latestDetails = rtCfgStatusInfodetailService.selectByInfoId(
                rtCfgStatusInfoDO.getStatusid());
        List<RtCfgStatusInfodetailDO> objects1 = new ArrayList<>();
        for (RtCfgStatusInfodetailDO latestDetail : latestDetails) {
            for (DspfStatusModultitemsubVO object : rtCfgBOMAndStatusInfoDTO.getDescrList()) {
                if (object.getDescrCode().equals(latestDetail.getSelectvaluecode())) {
                    latestDetail.setSelectvaluename(object.getDescrName());
                }
            }
            objects1.add(latestDetail);
        }
        if (objects1.size() <= 0) {
            return ResponseResult.success("200", "没有要修改的状态表");
        }
        // 单条更新已有明细
        if (!objects1.isEmpty()) {
            int updatedCount = 0;
            for (RtCfgStatusInfodetailDO detail : objects1) {
                int result = rtCfgStatusInfodetailService.updateRtCfgStatusInfodetail(detail);
                if (result > 0) {
                    updatedCount += result;
                }
            }
            if (updatedCount <= 0) {
                throw RTErrorCodeEnum.STATUS_INFO_CONTENT_IS_NULL.getException("明细表更新失败");
            }
        }


        //获取需求状态表模板内容
        if (StringUtils.isBlank(rtCfgBOMAndStatusInfoDTO.getProducttype())) {
            throw RTErrorCodeEnum.STATUS_INFO_CONTENT_IS_NULL.getException("机型不能为空");
        }
        if (StringUtils.isBlank(rtCfgBOMAndStatusInfoDTO.getDevcode())) {
            throw RTErrorCodeEnum.STATUS_INFO_CONTENT_IS_NULL.getException("开发令不能为空");
        }


        String objectNumber = rtCfgStatusInfoMapper.selectMoudleByProductType(STATUS_INFO_PARTTYPE,
                                                                              rtCfgBOMAndStatusInfoDTO.getProducttype(),
                                                                              STATUS_INFO_DEVCODE,
                                                                              rtCfgBOMAndStatusInfoDTO.getDevcode());

        if (StringUtils.isBlank(objectNumber)) {
            throw RTErrorCodeEnum.STATUS_INFO_CONTENT_IS_NULL.getException("未查询到机型");
        }

        List<String> alternateForPartNumbers = Arrays.asList(objectNumber);
        List<AlternateInfoVO> alternateInfoVOS = null;
        try {
            alternateInfoVOS = typlmPartAlternateService.batchQueryAlternates(
                    alternateForPartNumbers);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }

        List<TemplateInfoVO> oids = new ArrayList<>();
        for (AlternateInfoVO alternateInfoVO : alternateInfoVOS) {
            TemplateInfoVO templateInfoVO = new TemplateInfoVO(
                    String.valueOf(alternateInfoVO.getAlternateObjectMasterOid()),
                    alternateInfoVO.getAlternatempnname());
            if (templateInfoVO != null) {
                oids.add(templateInfoVO);
            }
        }

        if (oids.isEmpty()) {
            throw RTErrorCodeEnum.STATUS_INFO_CONTENT_IS_NULL.getException("未查询到绑定的需求模板，请重新再试！");
        }
        if (oids.size() > 1) {
            throw RTErrorCodeEnum.STATUS_INFO_CONTENT_IS_NULL.getException("该开发令和机型绑定了多个模板！");
        }
        List<DspfStatusModuleitemsubDTO> dspfStatusModuleitemsub = dspfStatusModuleitemsubMapper.getByDspfStatusModuleitemsub(
                new DspfStatusModuleitemsubDO(oids.get(0).getModuleId()));
        //        // 将 objects1 转换为 Map 提高查找效率
        //        Map<Long, RtCfgStatusInfodetailDO> detailMap = new HashMap<>();
        //        for (RtCfgStatusInfodetailDO detail : objects1) {
        //            detailMap.put(Long.valueOf(detail.getSid()), detail);
        //        }
        //
        //        // 根据明细数据筛选符合条件的对象
        //        for (DspfStatusModuleitemsubDTO dto : dspfStatusModuleitemsub) {
        //            if (dto.getIsDescribe() != null && dto.getIsDescribe() == 1) {
        //                RtCfgStatusInfodetailDO detail = detailMap.get(new Long(dto.getSid()));
        //                if (detail != null) {
        //                    objects.add(detail);
        //                }
        //            }
        //        }

        //        // 拼接选中值名称，使用下划线分隔 (例如: a_b_c)
        //        StringBuilder descriptionBuilder = new StringBuilder();
        //        StringBuilder shortDescriptionBuilder = new StringBuilder();
        //        for (RtCfgStatusInfodetailDO detail : objects) {
        //            if (detail.getSelectvaluename() != null) {
        //                if (descriptionBuilder.length() > 0) {
        //                    descriptionBuilder.append("_");
        //                }
        //                if (shortDescriptionBuilder.length() > 0) {
        //                    shortDescriptionBuilder.append("_");
        //                }
        //                DspfStatusModuleitemsubDTO dspfStatusModuleitemsubDTO = dspfStatusModuleitemsubMapper.selectBySid(
        //                        detail.getSid());
        //                if (dspfStatusModuleitemsubDTO != null) {
        //                    shortDescriptionBuilder.append(dspfStatusModuleitemsubDTO.getShortDescription());
        //                }
        //                descriptionBuilder.append(detail.getSelectvaluename());
        //            }
        //        }


        // 拼接选中值名称，使用下划线分隔 (例如: a_b_c)
        //全拼接
        StringBuilder descriptionBuilder = new StringBuilder();
        //短拼接
        StringBuilder shortDescriptionBuilder = new StringBuilder();
        for (RtCfgStatusInfodetailDO detail : latestDetails) {
            if (detail.getSelectvaluename() != null) {
                DspfStatusModuleitemsubDTO dspfStatusModuleitemsubDTO = dspfStatusModuleitemsubMapper.selectBySid(
                        detail.getSid());
                if (shortDescriptionBuilder.length() > 0) {
                    shortDescriptionBuilder.append("_");
                }
                if (descriptionBuilder.length() > 0) {
                    descriptionBuilder.append("_");
                }
                if (dspfStatusModuleitemsubDTO != null) {
                    if (dspfStatusModuleitemsubDTO.getIsDescribe() != null && dspfStatusModuleitemsubDTO.getIsDescribe() == 1) {
                        shortDescriptionBuilder.append(dspfStatusModuleitemsubDTO.getShortDescription());
                        shortDescriptionBuilder.append(detail.getSelectvaluename());
                    }
                    descriptionBuilder.append(dspfStatusModuleitemsubDTO.getDescrName());
                    descriptionBuilder.append(detail.getSelectvaluename());
                }
            }
        }


        // 更新主表的 短描述 字段
        rtCfgStatusInfoDO.setDescription(shortDescriptionBuilder.toString());
        //更新主表的长描述字段
        rtCfgStatusInfoDO.setDescriptionsplices(descriptionBuilder.toString());
        if (rtCfgStatusInfoMapper.updateByStatusId(rtCfgStatusInfoDO) <= 0) {
            throw RTErrorCodeEnum.STATUS_INFO_CONTENT_IS_NULL.getException("主表更新失败！");
        }
        return ResponseResult.success("保存成功!");

    }

    @Override
    public ResponseResult getReferenceSourceContent(RtCfgInfoDTO info) {
        if (info == null) {
            throw RTErrorCodeEnum.STATUS_INFO_CONTENT_IS_NULL.getException("参考EBOM或者参考成品码为空");
        }
        //参考成品码
        if (info.getRefermbomcode() != null && info.getRefermbomcode() != "") {
            //通过成品码获取最新的内容
            List<RtCfgStatusInfodetailDO> rtCfgStatusInfodetailDOS = rtCfgStatusInfoMapper.selectSorceContentByReferMbomCode(
                    info.getRefermbomcode());
            if (rtCfgStatusInfodetailDOS == null || rtCfgStatusInfodetailDOS.isEmpty()) {
                return ResponseResult.success(handleReferenceSourceData(info, info.getRefermbomcode()), "");
            } else {
                return ResponseResult.success(rtCfgStatusInfodetailDOS, "");
            }
        }
        //参考EBOM码
        if (info.getEbomcode() != null) {
            return ResponseResult.success(handleReferenceSourceData(info, info.getEbomcode()), "");
        }
        return ResponseResult.success("");
    }


    /**
     * 处理引用源数据
     */
    public List<RtCfgStatusInfodetailDO> handleReferenceSourceData(RtCfgInfoDTO info, String partNumber) {
        PartDO partDO = typlmPdmPartService.queryLastPartDoByPartNumber(partNumber);
        List<RtCfgStatusInfodetailDO> list = new ArrayList<>();
        if (partDO != null) {
            // 获取BOM结构树
            PartBomTreeByFilterVO bomTreeVO = commonService.queryChildParts(
                    partNumber,
                    partDO.getOid().toString(),
                    "Design",
                    Boolean.FALSE,
                    null,
                    "N",
                    Boolean.TRUE
            );
            List<PartBomTree> partBomTreeList = bomTreeVO.getPartBomTreeList();
            //获取模板的sub
            List<DspfStatusModuleitemsubDO> dspfStatusModuleitemsubDOS = dspfStatusModuleitemsubMapper.selectBymoduleid(
                    info.getModuleid());
            //新建一个map集合用来存放扩展属性
            Map<String, StatusInfoPartDetailVO> map = new HashMap<>();
            //存放终端的物料集合
            List<StatusInfoPartDetailVO> terminalPartList = new ArrayList<>();
            //存放动力的物料集合
            List<StatusInfoPartDetailVO> groupPartList = new ArrayList<>();
            //获取零部件的扩展属性  key和value都是内部名称
            partBomTreeList.stream().forEach(part -> {
                StatusInfoPartDetailVO statusInfoPartDetailVO = new StatusInfoPartDetailVO();
                List<String> nnameList = new ArrayList<>();
                if (part.getTypeName().equals("EBOM号")) {
                    //通过分类oid 获取所有的扩展属性信息
                    List<TyAttributeDefMapVO> attrDefMapList = this.typlmTypeService.queryInheritAttrDef(
                            part.getClassficationOid(), TableTypeConstrant.TY_CLASSIFICATION_OTYPE);
                    //获取所有扩展属性的内部名称
                    nnameList = attrDefMapList.stream().map(TyAttributeDefMapVO::getName).collect(
                            Collectors.toList());
                } else if (part.getTypeName().equals("成品码")) {
                    List<TyAttributeDefMapVO> attrDefMapList = this.typlmTypeService.queryInheritAttrDef(
                            part.getPartTypeOid(), TableTypeConstrant.TY_TYPE_OTYPE);
                    nnameList = attrDefMapList.stream().map(TyAttributeDefMapVO::getName).collect(
                            Collectors.toList());
                }
                if (nnameList == null || nnameList.isEmpty()) {
                    return;
                }
                //通过零部件的编码和扩展属性的内部名称的集合 获取扩展属性值
                List<IbaAttributeValueVO> ibaAttributeValueVOS = rtCfgStatusInfoMapper.selectIbaBypartNumbers(
                        part.getObjectNumber(), nnameList, null);
                if (ibaAttributeValueVOS != null && !ibaAttributeValueVOS.isEmpty()) {
                    statusInfoPartDetailVO.setIbaMapList(ibaAttributeValueVOS);
                    statusInfoPartDetailVO.setClassificationId(part.getClassficationOid());
                    statusInfoPartDetailVO.setName(part.getName());
                    statusInfoPartDetailVO.setPartNumber(part.getObjectNumber());
                    statusInfoPartDetailVO.setOid(part.getPartoid());
                    //                if (part.getTypeInnerName().equals(RTPlmConstant.PATTERNCODE)) {
                    //                    statusInfoPartDetailVO.setPartType("1");
                    //                } else if (part.getTypeInnerName().equals(RTPlmConstant.MATERIALCODE)) {
                    //                    statusInfoPartDetailVO.setPartType("0");
                    //                }
                    if (part.getTypeName().equals("图样代号")) {
                        statusInfoPartDetailVO.setPartType("1");
                    } else if (part.getTypeName().equals("物料码")) {
                        statusInfoPartDetailVO.setPartType("0");
                    }
                    map.put(part.getObjectNumber(), statusInfoPartDetailVO);
                    // 将父级过滤 并区分机组和动力的物料
                    if (part != null && part.getLevel() != null && !part.getLevel().equals(0)) {
                        Optional<IbaAttributeValueVO> developmentAttributeOpt = ibaAttributeValueVOS.stream()
                                .filter(iba -> RTPlmConstant.DEVELOPMENT.equals(iba.getName()))
                                .findFirst();
                        if (developmentAttributeOpt.isPresent()) {
                            //通过开发令 区分机组和动力
                            IbaAttributeValueVO iba = developmentAttributeOpt.get();
                            if (iba.getValueex() != null && iba.getValueex().length() > 0) {
                                String devCode = iba.getValueex().substring(0, 1);
                                String otypeByLineCode = getOtypeByLineCode(devCode);
                                if ("1".equals(otypeByLineCode)) {
                                    terminalPartList.add(statusInfoPartDetailVO);
                                } else if ("0".equals(otypeByLineCode)) {
                                    groupPartList.add(statusInfoPartDetailVO);
                                }
                            }
                        }
                    }
                }

            });
            for (DspfStatusModuleitemsubDO sub : dspfStatusModuleitemsubDOS) {
                if (3 == sub.getSubType()) {
                    RtCfgStatusInfodetailDO rtCfgStatusInfodetailDO = new RtCfgStatusInfodetailDO();
                    rtCfgStatusInfodetailDO.setSid(sub.getSid());
                    //获取Ebom上的测试要求
                    StatusInfoPartDetailVO statusInfoPartDetailVO = map.get(partNumber);
                    List<IbaAttributeValueVO> ibaMapList = statusInfoPartDetailVO.getIbaMapList();
                    ibaMapList.stream().forEach(iba -> {
                        if ("测试要求".equals(iba.getName())) {
                            // 通过枚举项的内部名称查询枚举项的oid
                            BigInteger oid = dspfStatusModuleitemsubMapper.selectEnumerationByName(iba.getNname());
                            if (oid != null && !"".equals(oid)) {
                                // 通过枚举项的oid查询枚举值
                                IdentifierEntity identifierEntity = new IdentifierEntity();
                                identifierEntity.setOid(oid);
                                List<EnumerationItemHandleVO> enumerationItems = this.typlmEnumerationItemService.queryEnumerationItemByDefOid(
                                        identifierEntity);
                                //通过枚举值的内部名称获取枚举值的显示名称
                                Optional<EnumerationItemHandleVO> first = enumerationItems.stream().filter(
                                        enumerationItemHandleVO -> enumerationItemHandleVO.getName()
                                                .equals(iba.getValueex())).findFirst();
                                rtCfgStatusInfodetailDO.setSid(sub.getSid());
                                rtCfgStatusInfodetailDO.setSelectvaluecode(iba.getValueex());
                                rtCfgStatusInfodetailDO.setSelectvaluename(first.get().getDisplayName());
                                list.add(rtCfgStatusInfodetailDO);
                            } else {
                                rtCfgStatusInfodetailDO.setSid(sub.getSid());
                                rtCfgStatusInfodetailDO.setSelectvaluecode(iba.getValueex());
                                rtCfgStatusInfodetailDO.setSelectvaluename(iba.getValueex());
                                list.add(rtCfgStatusInfodetailDO);
                            }
                        }
                    });
                } else if (4 == sub.getSubType()) {
                    RtCfgStatusInfodetailDO rtCfgStatusInfodetailDO = new RtCfgStatusInfodetailDO();
                    rtCfgStatusInfodetailDO.setSid(sub.getSid());
                    //获取Ebom上的认证要求
                    StatusInfoPartDetailVO statusInfoPartDetailVO = map.get(partNumber);
                    List<IbaAttributeValueVO> ibaMapList = statusInfoPartDetailVO.getIbaMapList();
                    if (ibaMapList != null && ibaMapList.size() > 0) {
                        ibaMapList.stream().forEach(iba -> {
                            if ("认证要求".equals(iba.getName())) {
                                rtCfgStatusInfodetailDO.setSid(sub.getSid());
                                String oid = rtCfgStatusInfoMapper.selectCertificationRequirementsByCertName(
                                        iba.getValueex());
                                rtCfgStatusInfodetailDO.setSelectvaluecode(oid);
                                rtCfgStatusInfodetailDO.setSelectvaluename(iba.getValueex());
                                list.add(rtCfgStatusInfodetailDO);
                            }
                        });
                    }

                } else if (8 == sub.getSubType()) {
                    //先判断是终端还是动力  0动力 groupPartList 1终端 terminalPartList
                    if (0 == sub.getProductClass()) {
                        //处理老系统的颜色类型
                        if (sub.getIscode() == null) {
                            List<RtCfgStatusInfodetailDO> rtCfgStatusInfodetailDOS = handleIbaAttributeValue(sub,
                                                                                                             groupPartList);
                            list.addAll(rtCfgStatusInfodetailDOS);
                            //处理老系统的 图号描述
                        } else if (sub.getIscode() == 1) {
                            List<StatusInfoPartDetailVO> collect = groupPartList.stream().filter(
                                    part -> part.getPartType().equals("1")).collect(Collectors.toList());
                            List<RtCfgStatusInfodetailDO> rtCfgStatusInfodetailDOS = handleIbaAttributeValue(sub,
                                                                                                             collect);
                            list.addAll(rtCfgStatusInfodetailDOS);
                            //处理老系统的 物料描述
                        } else if (sub.getIscode() == 0) {
                            List<StatusInfoPartDetailVO> collect = groupPartList.stream().filter(
                                    part -> part.getPartType().equals("0")).collect(Collectors.toList());
                            List<RtCfgStatusInfodetailDO> rtCfgStatusInfodetailDOS = handleIbaAttributeValue(sub,
                                                                                                             collect);
                            list.addAll(rtCfgStatusInfodetailDOS);
                        }
                    } else if (1 == sub.getProductClass()) {
                        //处理老系统的颜色类型
                        if (sub.getIscode() == null) {
                            List<RtCfgStatusInfodetailDO> rtCfgStatusInfodetailDOS = handleIbaAttributeValue(sub,
                                                                                                             terminalPartList);
                            list.addAll(rtCfgStatusInfodetailDOS);
                            //处理老系统的 图号描述
                        } else if (sub.getIscode() == 1) {
                            List<StatusInfoPartDetailVO> collect = terminalPartList.stream().filter(
                                    part -> part.getPartType().equals("1")).collect(Collectors.toList());
                            List<RtCfgStatusInfodetailDO> rtCfgStatusInfodetailDOS = handleIbaAttributeValue(sub,
                                                                                                             collect);
                            list.addAll(rtCfgStatusInfodetailDOS);
                            //处理老系统的 物料描述
                        } else if (sub.getIscode() == 0) {
                            List<StatusInfoPartDetailVO> collect = terminalPartList.stream().filter(
                                    part -> part.getPartType().equals("0")).collect(Collectors.toList());
                            List<RtCfgStatusInfodetailDO> rtCfgStatusInfodetailDOS = handleIbaAttributeValue(sub,
                                                                                                             collect);
                            list.addAll(rtCfgStatusInfodetailDOS);
                        }
                    }
                }
            }
        }
        return list.stream().distinct().collect(Collectors.toList());
    }

    /**
     * 处理引用源数据中 属性拼接的数据
     */
    public List<RtCfgStatusInfodetailDO> handleIbaAttributeValue(DspfStatusModuleitemsubDO sub,
                                                                 List<StatusInfoPartDetailVO> groupPartList
    ) {
        List<RtCfgStatusInfodetailDO> list = new ArrayList<>();
        //获取品类
        String partsCode = sub.getPartsCode();
        // 过滤这个品类的零部件
        List<StatusInfoPartDetailVO> partList = groupPartList.stream()
                .filter(part -> {
                    String partNumber = part.getPartNumber();
                    return partNumber != null && partsCode != null && partNumber.startsWith(partsCode);
                })
                .collect(Collectors.toList());

        String[] split = sub.getDescrCode().split(",");
        for (int i = 0; i < split.length; i++) {
            // 通过枚举项的内部名称查询枚举项的oid
            BigInteger oid = dspfStatusModuleitemsubMapper.selectEnumerationByName(sub.getDescrCode());
            StringBuffer stringBuffer = new StringBuffer();
            if (oid != null && !"".equals(oid)) {
                // 通过枚举项的oid查询枚举值
                IdentifierEntity identifierEntity = new IdentifierEntity();
                identifierEntity.setOid(oid);
                List<EnumerationItemHandleVO> enumerationItems = this.typlmEnumerationItemService.queryEnumerationItemByDefOid(
                        identifierEntity);
                //通过循环零部件获取引用源数据
                StringBuffer codeBuffer = new StringBuffer();
                StringBuffer nameBuffer = new StringBuffer();
                RtCfgStatusInfodetailDO rtCfgStatusInfodetailDO = new RtCfgStatusInfodetailDO();
                rtCfgStatusInfodetailDO.setSid(sub.getSid());
                partList.stream().forEach(part -> {
                    part.getIbaMapList().stream().forEach(iba -> {
                        // 通过枚举值的内部名称获取枚举值的显示名称
                        Optional<EnumerationItemHandleVO> first = enumerationItems.stream().filter(
                                enumerationItemHandleVO -> enumerationItemHandleVO.getName()
                                        .equals(iba.getValueex())).findFirst();
                        if (sub.getDescrCode().equals(iba.getNname())) {
                            // 添加下划线分隔符（除了第一个元素）
                            if (codeBuffer.length() > 0) {
                                codeBuffer.append("_");
                                nameBuffer.append("_");
                            }
                            codeBuffer.append(iba.getNname());
                            codeBuffer.append(iba.getValueex());
                            nameBuffer.append(iba.getName());
                            nameBuffer.append(first.isPresent() ? first.get().getDisplayName() : "");
                        }
                    });
                    if (nameBuffer.length()>0){
                        nameBuffer.append(";");
                    }

                });
                    if((nameBuffer.toString().contains(";"))){
                        rtCfgStatusInfodetailDO.setSelectvaluecode("/");
                    }else {
                        rtCfgStatusInfodetailDO.setSelectvaluecode(codeBuffer.toString());
                    }
                    rtCfgStatusInfodetailDO.setSelectvaluename(nameBuffer.toString());
                     list.add(rtCfgStatusInfodetailDO);

            }else {
                RtCfgStatusInfodetailDO rtCfgStatusInfodetailDO = new RtCfgStatusInfodetailDO();
                rtCfgStatusInfodetailDO.setSid(sub.getSid());
                StringBuffer codeBuffer = new StringBuffer();
                StringBuffer nameBuffer = new StringBuffer();

                // 通过循环零部件获取引用源数据
                partList.stream().forEach(part -> {
                    part.getIbaMapList().stream().forEach(iba -> {
                        // 添加下划线分隔符（除了第一个元素）
                        if (codeBuffer.length() > 0) {
                            codeBuffer.append("_");
                            nameBuffer.append("_");
                        }
                        codeBuffer.append(iba.getValueex());
                        codeBuffer.append(iba.getValueex());
                        nameBuffer.append(iba.getValueex());
                        nameBuffer.append(iba.getValueex());
                    });

                    if (nameBuffer.length()>0){
                        nameBuffer.append(";");
                    }

                });
                if((nameBuffer.toString().contains(";"))){
                    rtCfgStatusInfodetailDO.setSelectvaluecode("/");
                }else {
                    rtCfgStatusInfodetailDO.setSelectvaluecode(codeBuffer.toString());
                }
                rtCfgStatusInfodetailDO.setSelectvaluename(nameBuffer.toString());
                list.add(rtCfgStatusInfodetailDO);
            }
        }
        return list;
    }

    /**
     * 根据线体获取图号类型（机组、动力、传动）0动力/1机组/2传动
     *
     * @param lineCode
     * @return
     */
    private String getOtypeByLineCode(String lineCode) {
        ProductSpectrumDTO allProductSpectrum = devOrderService.getAllProductSpectrum();
        List<ProductSpectrumDTO> list = allProductSpectrum.getList();
        for (int i = 0; i < list.size(); i++) {
            String name = list.get(i).getName();
            List<ProductSpectrumDTO> dtoList = list.get(i).getList();
            for (int j = 0; j < dtoList.size(); j++) {
                String lineName = dtoList.get(j).getName();
                //获取产线名称最后一个字符为产线code
                String code = lineName.substring(lineName.length() - 1);
                if (lineCode.equals(code)) {
                    if ("OPE".equals(name)) {//终端（机组）
                        return "1";
                    }
                    if ("机组".equals(name)) {//终端（机组）
                        return "1";
                    }
                    if ("动力".equals(name)) {
                        return "0";
                    }
                    if ("传动".equals(name)) {
                        return "2";
                    }
                }

            }
        }
        return "";
    }

    @Override
    public ResponseResult getAllBomCode(Integer pageNumber, Integer pageSize) {
        try {
            // 设置分页参数
            PageHelper.startPage(pageNumber == null ? 1 : pageNumber,
                                 pageSize == null ? 10 : pageSize);

            // 查询所有数据
            List<ProductCodeAndDescriptionVO> allBomCode = rtCfgStatusInfoMapper.getAllBomCode();

            // 封装分页结果
            PageInfo<ProductCodeAndDescriptionVO> pageInfo = new PageInfo<>(allBomCode);

            return ResponseResult.success(pageInfo, "");
        } catch (Exception e) {
            throw RTErrorCodeEnum.STATUS_INFO_CONTENT_IS_NULL.getException("查询失败！");
        }
    }


    /**
     * @param statusId 机型表主键
     * @param productType 机型
     * @author dinglonghao
     * @date 2025/10/29$ 下午9:24$
     */
    public List<MatchResult> generateMaturity(String statusId, String productType) {
        if (StringUtils.isBlank(statusId) || StringUtils.isBlank(productType)) {
            TyException.throwSingleTyExceptionVarargs(ResponseCodeEnum.BIZ_WORKITEM_PARAM_NO);
        }
        List<StatusInfoDetailContentDO> statusInfoDetailContentDOS = rtCfgStatusInfodetailMapper.selectStatusByProductType(
                productType);
        //查询出需要比对的数据
        List<StatusInfoDetailContentDO> list = rtCfgStatusInfodetailMapper.selectStatusByStatusId(statusId);
        // 按 statusId 分组
        Map<String, List<StatusInfoDetailContentDO>> statusInfoDetailContentDOMap = statusInfoDetailContentDOS.stream()
                .filter(item -> !statusId.equals(item.getStatusId()))  // 增加过滤条件：排除getStatusId等于statusId的项
                .collect(Collectors.groupingBy(StatusInfoDetailContentDO::getStatusId));
        return match(list, statusInfoDetailContentDOMap);
    }

    /**
     * 比对算法
     */
    public List<MatchResult> match(List<StatusInfoDetailContentDO> currentData,
                                   Map<String, List<StatusInfoDetailContentDO>> historyData) {
        Map<String, StatusInfoDetailContentDO> currentIndex = buildFeatureIndex(currentData);
        List<MatchResult> results = new ArrayList<>(historyData.size());
        for (Map.Entry<String, List<StatusInfoDetailContentDO>> entry : historyData.entrySet()) {
            String version = entry.getKey();

            Set<String> historyFeatures = buildFeatureSet(entry.getValue());
            int matchedCount = 0;
            for (String feature : currentIndex.keySet()) {
                if (historyFeatures.contains(feature)) {
                    matchedCount++;
                }
            }
            double matchRate = 100.0 * matchedCount / currentData.size();
            results.add(new MatchResult(version, matchRate));
        }
        results.sort((a, b) -> Double.compare(b.matchRate, a.matchRate));
        return results;
    }

    /**
     * 构建索引（K: 字符串，V: 原始对象）
     */
    private Map<String, StatusInfoDetailContentDO> buildFeatureIndex(List<StatusInfoDetailContentDO> data) {
        Map<String, StatusInfoDetailContentDO> index = new HashMap<>();
        for (StatusInfoDetailContentDO dto : data) {
            index.put(createFeatureString(dto), dto);
        }
        return index;
    }

    /**
     * 构建集合（自动去重）
     */
    private Set<String> buildFeatureSet(List<StatusInfoDetailContentDO> data) {
        Set<String> features = new HashSet<>();
        for (StatusInfoDetailContentDO dto : data) {
            features.add(createFeatureString(dto));
        }
        return features;
    }

    /**
     * 生成字符串（忽略statusId）
     */
    private String createFeatureString(StatusInfoDetailContentDO dto) {
        return String.join("|",
                           dto.getProductType(),
                           dto.getProductCode(),
                           dto.getDescrName(),
                           dto.getSelectValueName(),
                           dto.getType(),
                           dto.getChildType(),
                           dto.getProductName()
        );
    }

    @Data
    public static class MatchResult {
        private final String historyVersion;
        private final double matchRate;
    }


    @Override
    public ResponseResult getStatusInfoByEnumItemList(List<EnumerationItemHandleVO> enumItemList) {
        //获取枚举项的oid
        BigInteger poid = enumItemList.stream()
                .filter(item -> item != null && item.getPoid() != null)
                .map(EnumerationItemHandleVO::getPoid)
                .findFirst()
                .orElse(null);
        //获取枚举项的详细信息
        IdentifierEntity identifierEntity = new IdentifierEntity();
        identifierEntity.setOid(poid);
        identifierEntity.setOtype(TableTypeConstrant.TY_ENUMERATIONDEF_OTYPE);
        EnumDetailDTO enumDetailByEntity = this.typlmEnumerationService.getEnumDetailByEntity(identifierEntity);
        //获取枚举项的内部名称
        String nname = enumDetailByEntity.getName();
        //获取枚举项的显示名称
        String displayName = enumDetailByEntity.getDisplayName();
        //把枚举值的内部名称拿出来
        List<String> childrenNname = enumItemList.stream()
                .filter(Objects::nonNull)  // 过滤掉null元素
                .map(EnumerationItemHandleVO::getName)  // 提取name属性
                .filter(Objects::nonNull)  // 过滤掉null的name值
                .collect(Collectors.toList());
        //先通过枚举项的oid查询引用状态需求表
        List<RTEngraveDemandStatusVO> statusInfoDetailContentDOList = rtCfgStatusInfoMapper.selectStatusInfoDetailContentDOByPoid(
                poid, childrenNname);
        return ResponseResult.success(statusInfoDetailContentDOList, "");
    }

    @Override
    public ResponseResult getProductTypeByDevCode(String devCode) {
        String lineCode = devCode.substring(0, 1);
        ProductSpectrumDTO allProductSpectrum = devOrderService.getAllProductSpectrum();
        List<ProductSpectrumDTO> list = allProductSpectrum.getList();
        for (int i = 0; i < list.size(); i++) {
            String name = list.get(i).getName();
            List<ProductSpectrumDTO> dtoList = list.get(i).getList();
            for (int j = 0; j < dtoList.size(); j++) {
                String lineName = dtoList.get(j).getName();
                //获取产线名称最后一个字符为产线code
                String code = lineName.substring(lineName.length() - 1);
                if (lineCode.equals(code)) {
                    return ResponseResult.success(lineName, "请求成功");
                }

            }
        }
        return ResponseResult.success("", "请求成功");
    }

    @Override
    public ResponseResult getMaterielCodeByProductCode(String productCode) {
        PartDO partDO = typlmPdmPartService.queryLastPartDoByPartNumber(productCode);

        // 若未查询到对应物料，直接返回空列表
        if (partDO == null) {
            return ResponseResult.success(Collections.emptyList(), "");
        }

        // 查询BOM结构
        PartBomTreeByFilterVO bomTreeVO = commonService.queryChildParts(
                partDO.getPartnumber(),
                partDO.getOid().toString(),
                "Design",
                Boolean.FALSE,
                null,
                "N",
                Boolean.TRUE
        );

        // 提取BOM中符合条件的物料码
        List<String> materialCodes = Optional.ofNullable(bomTreeVO)
                // 若BOM树为空，直接返回空列表
                .map(PartBomTreeByFilterVO::getPartBomTreeList)
                .orElse(Collections.emptyList())
                .stream()
                // 过滤：层级不为"0"
                .filter(partBomTree -> !Objects.equals(partBomTree.getLevel(), "0"))
                // 类型为"物料码"
                .filter(partBomTree -> Objects.equals(partBomTree.getTypeName(), "物料码"))
                // 提取物料编号
                .map(PartBomTree::getObjectNumber)
                // 去重
                .distinct()
                .collect(Collectors.toList());

        return ResponseResult.success(materialCodes, "");
    }

    @Override
    public ResponseResult addZd(List<ZdDbWithFormoid> list) {

        String zdnumber = serialNumberService.getSerialNumber("ZD", 7);

        List<MultipartFile> fileList = new ArrayList<>();  //附件
        FormDataDTO formDataDTO = new FormDataDTO();
        // 3. 生成表单JSON字符串
        String formData = this.generateFormData(list);
        formDataDTO.setFormDataStr(formData);// 表单中内容赋值
        formDataDTO.setFormtemplateotype("ty.inteplm.form.CTyFormTemplate");
        formDataDTO.setFormtemplateoid(new BigInteger("751426729789177856"));
        formDataDTO.setContaineroid(new BigInteger("747656141957578752"));
        formDataDTO.setContainerotype("ty.inteplm.product.CTyPDMProduct");
        formDataDTO.setDomainoid(new BigInteger("747656180624867328"));
        formDataDTO.setDomainotype("ty.inteplm.domain.CTyDomain");
        formDataDTO.setCabinetotype("ty.inteplm.folder.CTyCabinet");
        formDataDTO.setSubfolderoid(new BigInteger("747656180624867328"));
        formDataDTO.setSubfolderotype("ty.inteplm.folder.CTySubFolder");
        formDataDTO.setLifecyclestageotype("ty.inteplm.lifecyclestage.CTyLifecycleStage");
        formDataDTO.setLifecycletemplateotype("ty.inteplm.lifecyclestage.CTyLifecycleTemplate");
        formDataDTO.setTeamotype("ty.inteplm.team.CTyTeam");
        formDataDTO.setTeamtemplateotype("ty.inteplm.team.CTyTeamTemplate");
        formDataDTO.setObjectNumber(zdnumber);//物料编码
        formDataDTO.setTypeotype("ty.inteplm.type.CTyTypeDef");
        formDataDTO.setCreatorotype("ty.inteplm.user.CTyUser");
        formDataDTO.setUpdatorotype("ty.inteplm.user.CTyUser");
        formDataDTO.setOwnerotype("ty.inteplm.user.CTyUser");
        formDataDTO.setOwneroid(new BigInteger("105"));//**
        formDataDTO.setClassficationotype("ty.inteplm.classification.CTyClassification");
        formDataDTO.setClassificationotype("ty.inteplm.classification.CTyClassification");
        formDataDTO.setTypeoid(new BigInteger("747438986741579776"));
        formDataDTO.setName(zdnumber);//物料名称
        List<FormDataFileMarkDTO> formDataFileMarkDTOList = new ArrayList<>();
        List<BigInteger> addFileList = new ArrayList<>();
        List<BigInteger> removeFileList = new ArrayList<>();
        FormFileDTO formFileDTO = new FormFileDTO();
        formFileDTO.setAddFileList(addFileList);
        formFileDTO.setRemoveFileList(removeFileList);
        FormDataDO formDataDO = tyFormDataExtService.createFormDataWithFile(formDataDTO, formDataFileMarkDTOList,
                                                                            fileList, formFileDTO);
        return ResponseResult.success(formDataDO, "操作成功");
    }

    private String generateFormData(List<ZdDbWithFormoid> list) {
        // 1. 构建主表单JSON对象
        JSONObject mainForm = new JSONObject();

        // 2. 填充主表单固定字段（非子表单部分）
        mainForm.put("input87825", list.get(0).getAppointreasontext()); // 指定原因
        mainForm.put("input49647", "");       //内容

        mainForm.put("radio67692", list.get(0).getRadio67692());
        mainForm.put("input87825", list.get(0).getInput87825());
        mainForm.put("radio99177", list.get(0).getRadio99177());
        mainForm.put("input49564", list.get(0).getInput49564());
        mainForm.put("textarea11936", list.get(0).getTextarea11936());
        //
        mainForm.put("addFileList", new JSONArray()); // 无附件

        // 3. 构建子表单（subform67098）数组（支持多条数据，这里以单条为例）
        JSONArray subformArray = new JSONArray();


        // 4. 填充子表单字段（从DTO中提取数据）
        for (ZdDbWithFormoid dto : list) {
            JSONObject subformItem = new JSONObject();
            subformItem.put("_rowId_", "id" + System.currentTimeMillis()); // 动态生成行ID
            subformItem.put("input17817", dto.getChangeType());           // 需求类型：新增/修改
            subformItem.put("input75631", dto.getCustomerName());         // 客户名称
            subformItem.put("input94778", dto.getCustomerCode());         // 客户编码
            subformItem.put("input80138", dto.getDevCode());              // 开发令
            subformItem.put("input11655", dto.getProductType());          // 机型
            subformItem.put("input66947", dto.getMaterialCode());         // 物料编码
            subformItem.put("input20325", dto.getPartName());             // 物料名称
            subformItem.put("input80487", dto.getSupplierName());         // 供应商名称
            subformItem.put("input7629", dto.getSupplierCode());          // 供应商编码（可为空）
            subformItem.put("input21986", dto.getOrderNo());              // 订单号
            subformItem.put("input68758", dto.getAppointType());          // 指定类型：长期/临时
            subformItem.put("input111716", dto.getEndTime());             // 结束日期
            subformItem.put("input112797", dto.getOrderItemNo());         // 项次号
            subformItem.put("input94969", dto.getPartsCode());            // 成品码
            subformItem.put("input40813", dto.getStatus());                         // 状态（固定值）
            // 5. 将子表单项添加到数组
            subformArray.add(subformItem);
        }
        mainForm.put("subform67098", subformArray);

        // 6. 转换为JSON字符串并返回
        return mainForm.toJSONString();
    }

}




